﻿using CommandService;
using Entity.FrameEntity;
using Entity;
using SysFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tools;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Entity.DbEntity.sys;
using System.Data;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Tokens;
using System.Security.Principal;
using Azure;
using System.Drawing.Printing;
using Entity.ViewEntity.barPrint.ToClient;
using log4net;
using Entity.ViewEntity.barPrint.FromClient;
using System.Reflection.Emit;
using System.Xml.Linq;
using System.ComponentModel.Design;
using System.Collections.Specialized;
using static System.Runtime.CompilerServices.RuntimeHelpers;
using Entity.DbEntity;
using System.Collections;
using Microsoft.Data.SqlClient.DataClassification;
using System.Reflection;
using Microsoft.VisualBasic;
using static System.Formats.Asn1.AsnWriter;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Math;
using DocumentFormat.OpenXml.Bibliography;



namespace BLL
{
    public class BarBLL : PubMethod
    {
        Commands cmd;
        ReturnResult rsl;
        OperateModel oper;
        List<OperateModel> operList;
        ILog _log;

        public BarBLL()
        {
            cmd = new Commands();

            _log = LogManager.GetLogger(this.GetType().Name);
        }

        /// <summary>
        /// 条码数据列表展示
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getBarCodeList(string pageIndex, string pageSize, ref string pageCount, string condition, string orderStr, string baseCode)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }

                #region 检索条件
                sb.Append(" baseCode='" + baseCode + "' ");
                //sb = CreateSelectCondition(sb, condition);
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (obj.Name == "barStatus")
                        {
                            if (string.IsNullOrWhiteSpace(obj.Value.ToString()))
                            {
                                sb.Append(" and barStatus!='bar-drop' ");
                            }
                        }
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "wareHouse")
                            {
                                sb.Append(" wareHouse ='" + obj.Value.ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }
                }
                #endregion

                if (string.IsNullOrWhiteSpace(orderStr))
                {
                    //orderStr = "id desc";
                    orderStr = "charindex(barStatus,'need-in,need-check,need-out,bar-finish,used-finish'),convert(decimal(18,2),number) desc";
                }
                var list = cmd.PageList("V_BarCode_Info", pageIndex, pageSize, sb.ToString(), orderStr, ref pageCount);

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 条码作废
        /// </summary>
        /// <param name="barCode">条码编码</param>
        /// <param name="userCode">操作人员编码</param>
        /// <param name="baseCode">账套</param>
        /// <param name="dept">操作人部门</param>
        /// <returns></returns>
        public ReturnResult DropBarCode(string barCode, string userCode, string baseCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            StringBuilder sb = new StringBuilder();
            try
            {
                //验证
                if (string.IsNullOrWhiteSpace(barCode))
                {
                    rsl.Message = "没有获取到条码";
                    return rsl;
                }

                string barType = "";  //条码类别
                string costPlan = "";  //作废条码关联的计划号

                #region 作废条件(条码状态) 限制 （生产条码   need-in 和 need-check 【used-finish也可以 】可以作废    ， 期初、采购不限制状态  ）
                sb.Append("select barType,barStatus,gxCode,barType,costPlan from bar_ProductBarCode_info where barCode='" + barCode + "'");
                var barTable = cmd.GetDataTable(sb.ToString());  //条码表
                if (barTable.Rows.Count > 0)
                {
                    barType = barTable.Rows[0]["barType"].ToString();
                    costPlan = barTable.Rows[0]["costPlan"].ToString();

                    if (barTable.Rows[0]["barStatus"].ToString() == "bar-drop")
                    {
                        rsl.Message = "条码已作废!";
                        rsl.Result = false;
                        return rsl;
                    }
                    if ((barType == "SC") && barTable.Rows[0]["barStatus"].ToString() != "need-in" && barTable.Rows[0]["barStatus"].ToString() != "need-check" && barTable.Rows[0]["barStatus"].ToString() != "used-finish")
                    {
                        rsl.Message = "条码此状态严禁作废";
                        rsl.Result = false;
                        return rsl;
                    }

                }
                else
                {
                    rsl.Message = "条码不存在!";
                    rsl.Result = false;
                    return rsl;
                }

                #endregion

                #region 目标作废条码 作为（没有作废的条码的关联条码）被使用时，不能作废   used-finish时会在此验证，如果还有关联码，不能作废
                sb.Clear();
                sb.Append("select barCode from bar_ProductBarCode_info where relationBar='" + barCode + "' and barStatus!='bar-drop' ");
                barTable = cmd.GetDataTable(sb.ToString());  //条码表
                if (barTable.Rows.Count > 0)
                {
                    rsl.Message = "该条码已被条码：" + barTable.Rows[0][0].ToString() + "关联使用，禁止作废";
                    rsl.Result = false;
                    return rsl;

                }
                #endregion

                #region 条码  有关联条码时，关联条码不在库时，不能作废
                sb.Clear();
                sb.Append("select rb.barCode,rb.barStatus from bar_ProductBarCode_info rb ");
                sb.Append("inner join bar_ProductBarCode_info b on b.relationBar=rb.barCode ");
                sb.Append("where b.barCode='" + barCode + "' ");
                barTable = cmd.GetDataTable(sb.ToString());  //条码表
                if (barTable.Rows.Count > 0 && barTable.Rows[0]["barStatus"].ToString() == "bar-finish")
                {
                    rsl.Message = "该条码的关联条码：" + barTable.Rows[0]["barCode"].ToString() + "已出库，禁止作废";
                    rsl.Result = false;
                    return rsl;

                }
                #endregion
                #region 获得作废的关联条码(Ning)
                //var bStr = "";
                //foreach (DataRow row in barTable.Rows)
                //{
                //    bStr = "'" + row["barCode"].ToString() + "',";
                //}
                //bStr = bStr.TrimEnd(',');
                ////var bStr = barTable.Rows[0]["barCode"].ToString();
                #endregion

                DbProductBarCode bar;

                if (barType == "SC")
                {
                    #region 生产条码作废   考虑用料废料等
                    //作废条码 的 关联条码 使用完成了，还允不允许作废？
                    //使用完成 状态是录废料信息的时候勾选的 是否使用完成 ，按说没用完不会选的

                    //作废码 的 关联条码是原料码 红字出库 数量加回，计划用料表数量红冲掉  ；   是生产码，数量加回

                    DBPlanYongLiao yongLiao;
                    DBPlanWaste waste;

                    #region 将条码的 关联条码 相关用料 做红字材料出库单 ， 将关联条码数量加回，计划用料表数量红冲掉

                    var dept = "5"; //旭日：3 生产部  5 库存部   本地 ：5 二车间
                    var wareHouse = "8";  //旭日:车间库
                    #region 查寻关联条码所属仓库（Ning）
                    //sb.Clear();
                    //sb.Append(" select wareHouse from bar_ProductBarCode_info where barCode in (" + bStr + ")");
                    //sb.Append(" group by wareHouse order by wareHouse desc ");
                    //var wTable = cmd.GetDataTable(sb.ToString());
                    //int wnum = 0;
                    //foreach (DataRow r in wTable.Rows)
                    //{
                    //    if (!string.IsNullOrWhiteSpace(r["wareHouse"].ToString()))
                    //    {
                    //        wareHouse = r["wareHouse"].ToString();
                    //        wnum++;
                    //    }
                    //}
                    //if (wnum > 1)
                    //{
                    //    rsl.Message = "关联条码存在多个仓库！";
                    //    return rsl;
                    //}
                    #endregion

                    sb.Clear();
                    sb.Append("select b.count,bn.barType,pm.*,bp.*,bo.unit,bo.proWeight,bo.proMeter ");   //关联条码现有数量 proWeight,proMeter
                    sb.Append("from bar_BarPrintLogs bp ");
                    sb.Append("left join (select count(*) count,newBar,oldBar from bar_BarPrintLogs group by newBar,oldBar) b on b.oldBar=bp.oldBar and b.newBar=bp.newBar ");   //24.11.15新增 11.21修改
                    sb.Append("inner join bar_ProductBarCode_info bn on bn.barCode=bp.newBar  ");
                    sb.Append("inner join bar_ProductBarCode_info bo on bo.barCode=bp.oldBar ");
                    //sb.Append("left join pi_PlanMaterial_list pm on pm.reBarCode=bp.oldBar where newBar ='" + barCode + "' ");  //打印记录表，记录的条码的用料
                    sb.Append("left join pi_PlanMaterial_list pm on pm.reBarCode=bp.oldBar and bp.mCode = pm.mCode where bp.newBar ='" + barCode + "' ");  //打印记录表，记录的条码的用料
                    //作废码 的 关联条码是原料码
                    sb.Append("and (bn.barType!='SC' and ( bo.unit='kg' and  Convert(decimal(18,2),pm.number)=Convert(decimal(18,2),bp.useWeight) ) ");
                    sb.Append("or ( bo.unit != 'kg' and  Convert(decimal(18, 2), pm.number) = Convert(decimal(18, 2), bp.useMeter)) ");
                    //作废码 的 关联条码是生产码
                    sb.Append("or (bn.barType='SC' and pm.number is null or Convert(decimal(18, 2), pm.number)>0 )) ");
                    //sb.Append("and pm.number>0 ");
                    sb.Append("order by pm.id desc ");

                    var bTable = cmd.GetDataTable(sb.ToString());//条码的用料信息
                    if (bTable.Rows.Count > 0)
                    {
                        #region 获取材料出库默认的 业务类型 、部门  、仓库
                        sb.Clear();
                        sb.Append("seleCt parValue,parCode from sys_parameters_info where parCode like '%Style' and isdel=0 ");
                        var table = cmd.GetDataTable(sb.ToString());

                        var crdcode = "22"; //旭日环境
                        crdcode = table.Select("parCode='pom_Rd_Style'")[0]["parValue"].ToString();

                        dept = table.Select("parCode='all_Dept_Style'")[0]["parValue"].ToString();

                        #region 查询条码库存（Ning）客户说不会出现多个仓库
                        var Bars = "";
                        foreach (DataRow r in bTable.Rows)
                        {
                            Bars += "'" + r["oldBar"].ToString() + "',";
                        }
                        Bars = Bars.TrimEnd(',');

                        sb.Clear();
                        sb.Append(" select wareHouse from bar_ProductBarCode_info where barCode in (" + Bars + ") ");
                        sb.Append(" group by wareHouse order by wareHouse desc ");
                        var wTable = cmd.GetDataTable(sb.ToString());
                        int wnum = 0;
                        foreach (DataRow r in wTable.Rows)
                        {
                            if (!string.IsNullOrWhiteSpace(r["wareHouse"].ToString()))
                            {
                                wareHouse = r["wareHouse"].ToString();
                                wnum++;
                            }
                        }
                        if (wnum > 1)
                        {
                            rsl.Message = "关联条码存在多个仓库！";
                            return rsl;
                        }
                        #endregion
                        //wareHouse = table.Select("parCode='pom_Ware_Style'")[0]["parValue"].ToString();
                        #endregion

                        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                        Dictionary<string, string> dic;
                        List<string> bars = new List<string>();

                        foreach (DataRow dr in bTable.Rows)
                        {
                            #region 将关联条码数量加回
                            bar = new DbProductBarCode();
                            bar.barCode = dr["oldBar"].ToString();
                            bar.proWeight = (double.Parse(dr["useWeight"].ToString())/int.Parse(dr["count"].ToString()) + double.Parse(dr["proWeight"].ToString())).ToString("0.00");   //24.11.15 调整。新增/count
                            bar.proMeter = (double.Parse(dr["useMeter"].ToString()) / int.Parse(dr["count"].ToString()) + double.Parse(dr["proMeter"].ToString())).ToString("0.00");   //24.11.15 调整。新增/count
                            if (dr["unit"].ToString() == "kg")
                                bar.number = bar.proWeight;
                            else
                                bar.number = bar.proMeter;

                            oper = new OperateModel();
                            oper.Data = bar;
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "barCode";
                            operList.Add(oper);
                            #endregion


                            //计划（条码）用料不为空，即条码做了材料出库
                            if (!string.IsNullOrWhiteSpace(dr["number"].ToString()))
                            {
                                double addNum = 0;
                                if (dr["unit"].ToString() == "kg")
                                    addNum = double.Parse(dr["useWeight"].ToString()) / int.Parse(dr["count"].ToString());
                                else
                                    addNum = double.Parse(dr["useMeter"].ToString()) / int.Parse(dr["count"].ToString());

                                #region 计划用料表数量红冲掉   (即新增负数的用料信息)
                                yongLiao = new DBPlanYongLiao();
                                yongLiao.plCode = dr["plCode"].ToString();
                                yongLiao.proCode = dr["proCode"].ToString();
                                yongLiao.batch = dr["batch"].ToString();
                                yongLiao.reBarCode = dr["oldBar"].ToString();
                                //yongLiao.number = "-" + dr["number"].ToString();
                                yongLiao.number = "-" + addNum.ToString("0.00");
                                yongLiao.uPrice = dr["uPrice"].ToString();
                                yongLiao.total = (decimal.Parse(yongLiao.number) * decimal.Parse(yongLiao.uPrice)).ToString("0.00");
                                yongLiao.mType = dr["mType"].ToString();
                                yongLiao.memo = "条码作废，用料红冲";
                                yongLiao.valueType = "-1";

                                oper = new OperateModel();
                                oper.Data = yongLiao;
                                oper.Types = OperateModel.OperateType.Add;
                                operList.Add(oper);
                                #endregion

                                #region 构建 材料出库单 参数

                                dic = new Dictionary<string, string>();
                                dic["proCode"] = dr["proCode"].ToString();
                                dic["proName"] = "";
                                //dic["number"] = "-" + dr["number"].ToString();
                                dic["number"] = "-" + addNum.ToString("0.00");
                                dic["cu_batch"] = dr["batch"].ToString();
                                dic["iunitcost"] = dr["uPrice"].ToString();//单价
                                //dic["iprice"] = (decimal.Parse("-" + dr["number"].ToString()) * decimal.Parse(dr["uPrice"].ToString())).ToString("0.00");//总金额
                                dic["iprice"] = (decimal.Parse("-" + addNum.ToString("0.00")) * decimal.Parse(dr["uPrice"].ToString())).ToString("0.00");//总金额

                                dic["plCode"] = costPlan;//作废条码关联的计划号

                                list.Add(dic);

                                bars.Add(dr["oldBar"].ToString());//出库条码

                                #endregion

                            }

                        }

                        #region  （如果有做材料出库）   将条码的 关联条码 相关用料 做红字材料出库单
                        if (list.Count > 0 )
                        {
                            U8Order order = new U8Order();
                            rsl = order.tyInOut(list, bars, wareHouse, crdcode, dept, baseCode, userCode, "MaterialOut", "0");

                            var U8Codes = string.Empty;
                            var U8Message = string.Empty;
                            var errBarCodes = new List<string>();//调用接口失败的条码

                            #region 接口返回结果   false或有错误直接返回
                            if (rsl.Result)
                            {
                                if (rsl.Data != null)
                                {
                                    List<InOutResult> iorList = new List<InOutResult>();
                                    iorList = (List<InOutResult>)rsl.Data;
                                    if (iorList.Count > 0)
                                    {
                                        U8Codes = "";
                                        foreach (InOutResult ior in iorList)
                                        {
                                            if (!string.IsNullOrWhiteSpace(ior.SuccOrderCode))
                                            {
                                                #region 调用接口成功
                                                U8Codes += ior.SuccOrderCode + ",";

                                                #region 返回错误信息和错误条码
                                                ErrorResult err = (ErrorResult)ior.ErrorInfo;
                                                if (err != null)
                                                {
                                                    if (!string.IsNullOrWhiteSpace(err.ErrorMsg))
                                                    {
                                                        U8Message += JsonConvert.SerializeObject(err.BarCodes) + "：" + err.ErrorMsg + "\n";//U8返回来的错误信息
                                                    }
                                                }
                                                #endregion

                                                #endregion

                                            }
                                            else
                                            {
                                                #region 返回错误信息和错误条码
                                                ErrorResult err = (ErrorResult)ior.ErrorInfo;
                                                if (err != null)
                                                {
                                                    if (!string.IsNullOrWhiteSpace(err.ErrorMsg))
                                                    {
                                                        U8Message += JsonConvert.SerializeObject(err.BarCodes) + "：" + err.ErrorMsg + "\n";//U8返回来的错误信息
                                                    }
                                                    if (err.BarCodes != null && err.BarCodes.Count > 0)
                                                    {
                                                        errBarCodes.AddRange(err.BarCodes);
                                                    }
                                                }
                                                #endregion
                                            }

                                        }
                                    }
                                }
                                if (!string.IsNullOrWhiteSpace(U8Message))
                                {
                                    U8Message = "U8接口错误：" + U8Message;
                                    rsl.Message = U8Message;
                                    rsl.Result = false;
                                    return rsl;
                                }

                                _log.Info("(DropBarCode)条码作废时关联条码红字材料出库成功，单号为：" + U8Codes.TrimEnd(','));
                            }
                            else
                            {
                                rsl.Message = "关联条码红字材料出库失败：" + rsl.Message;
                                _log.Info("(DropBarCode)条码作废时关联条码红字材料出库失败：" + rsl.Message);
                                return rsl;
                            }
                            #endregion
                        }

                        #endregion

                    }

                    #endregion

                    //【废料退回】 好像应该是作废条码的 废料信息  但是跟上面冲突，如果作废条码被用作关联条码，是不允许作废的

                    //考虑 没有关联作废码打码， 但是选了这个码录了废料了
                    #region 【作废条码】如果 有废料信息 并且已经废料入库  将（计划工序的全部）废料做 红字 其他入，并作废废料信息  

                    sb.Clear();
                    //sb.Append("select pw.* from pi_PlanWaste_info pw inner join bar_ProductBarCode_info b on  b.barCode=pw.reBarCode  "); // b.relationBar=pw.reBarCode
                    //sb.Append("where isdel=0 and barCode='"+barCode+ "' order by plCode,gxCode ");

                    sb.Append("select pw.* from pi_PlanWaste_info pw  ");
                    sb.Append("inner join (select plCode,gxCode from pi_PlanWaste_info where reBarCode = '" + barCode + "' and isdel=0 group by plCode,gxCode ) p ");
                    sb.Append("on pw.plCode = p.plCode and pw.gxCode = p.gxCode ");
                    sb.Append("where pw.isdel=0 order by plCode,gxCode ");

                    bTable = cmd.GetDataTable(sb.ToString());//条码 相关的计划工序 的废料信息
                    if (bTable.Rows.Count > 0)
                    {
                        #region 获取废料编码、 名称
                        sb.Clear();
                        sb.Append("select parValue,parCode from sys_parameters_info where parCode in('flInWh','flCode') ");
                        var dt = cmd.GetDataTable(sb.ToString());

                        var flCode = "";
                        var flName = "";
                        var rows = dt.Select("parCode = 'flCode' ");
                        if (rows.Length > 0)
                        {
                            var values = rows[0]["parValue"].ToString().Split(',');
                            flCode = values[0];
                            flName = values[1];
                        }
                        else
                        {
                            rsl.Message = "无废料编码信息";
                            return rsl;
                        }
                        #endregion

                        #region 其他入库 入的 仓库 和 入库类别 信息
                        wareHouse = "003";
                        var rdcode = "31";
                        rows = dt.Select("parCode = 'flInWh' ");
                        if (rows.Length > 0)
                        {
                            var values = rows[0]["parValue"].ToString().Split(',');
                            wareHouse = values[0];
                            rdcode = values[1];
                        }
                        #endregion

                        var flNum = 0m;  //废料数量
                        List<string> pgList = new List<string>(); //需要修改回 废料待入库状态 的计划工序
                        var table = new DataTable();  //废料信息
                        table.Columns.Add("number");
                        table.Columns.Add("proCode");
                        table.Columns.Add("proName");
                        table.Columns.Add("cu_batch");
                        //table.Columns.Add("orderCode");

                        foreach (DataRow dr in bTable.Rows)
                        {
                            #region 作废废料信息
                            waste = new DBPlanWaste();
                            waste.isdel = 1;
                            waste.delMsg = userCode + "," + getNow() + ",条码作废，作废相关废料信息";
                            waste.id = Convert.ToInt32(dr["id"].ToString());

                            oper = new OperateModel();
                            oper.Data = waste;
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "id";
                            operList.Add(oper);
                            #endregion

                            //计划 工序 已做废料入库
                            if (!string.IsNullOrWhiteSpace(dr["orderCode"].ToString()))
                            {
                                var key = dr["plCode"].ToString() + "-" + dr["gxCode"].ToString();

                                if (!pgList.Contains(key))
                                {
                                    pgList.Add(key);
                                }


                                flNum += decimal.Parse(dr["number"].ToString());

                            }

                        }

                        #region （如果已废料入）  将【作废条码】的 废料做 红字其他入  
                        if (flNum > 0)
                        {
                            U8Order order = new U8Order();

                            #region 废料数据
                            var dataRow = table.NewRow();
                            dataRow["number"] = -flNum;
                            dataRow["proCode"] = flCode;
                            dataRow["proName"] = flName;
                            dataRow["cu_batch"] = "";
                            //dataRow["orderCode"] = "";

                            table.Rows.Add(dataRow);
                            #endregion

                            rsl = order.FlOtherIn(table, userCode, baseCode, wareHouse, dept, rdcode, "0");

                            #region 接口返回结果   false或有错误直接返回
                            if (rsl.Result)
                            {
                                _log.Info("(DropBarCode)条码作废时废料红字其他入库成功，单号为：" + rsl.Data);
                            }
                            else
                            {
                                rsl.Message = "废料红字其他入库失败：" + rsl.Message;
                                _log.Info("(DropBarCode)条码作废时废料红字其他入库失败：" + rsl.Message);
                                return rsl;
                            }
                            #endregion
                        }

                        #endregion

                    }


                    #endregion


                    #endregion
                }

                //采购、期初只改状态
                #region 改变条码状态
                bar = new DbProductBarCode();
                bar.barCode = barCode;
                bar.barStatus = "bar-drop";
                bar.memo = string.Format("条码作废({0},{1})", userCode, getNow());
                oper = new OperateModel();
                oper.Data = bar;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "barCode";
                operList.Add(oper);
                #endregion

                rsl = cmd.MoreUpdate(operList);
                if (rsl.Result)
                {
                    rsl.Data = "作废成功！";
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 出入库编码数据查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getBarEntryRecords(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                sb.Append(" 1=1 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "sDate")
                            {
                                sb.Append("convert(date,createtime)>='" + obj.Value.ToString() + "' ");
                            }
                            else if (obj.Name == "eDate")
                            {
                                sb.Append("convert(date,createtime)<='" + obj.Value.ToString() + "' ");
                            }
                            else if (obj.Name == "barCode")
                            {
                                sb.Append(" mCode in (select mCode from bar_BarEntryRecords_list where barCode like '%" + obj.Value.ToString() + "%' ) ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }
                }
                var list = cmd.PageList("V_BarEntoryRecords_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                if (list.Count > 0)
                {
                    string mCodes = "";
                    for (int i = 0; i < list.Count; i++)
                    {
                        mCodes += "'" + list[i]["mCode"].ToString() + "',";
                    }
                    sb.Clear();
                    sb.Append("select barcode,mCode,num from bar_BarEntryRecords_list where status='Y'");
                    sb.Append("and mCode in(" + mCodes.TrimEnd(',') + ")");
                    var lTable = cmd.GetDataTable(sb.ToString());
                    for (int i = 0; i < list.Count; i++)
                    {
                        var dr = lTable.Select("mCode='" + list[i]["mCode"].ToString() + "'");
                        string sum = "0";

                        foreach (DataRow r in dr)
                        {
                            if (r["num"] != null && !string.IsNullOrWhiteSpace(r["num"].ToString()))
                            {
                                //int intResult;
                                //bool success = int.TryParse(r["num"].ToString(), out intResult);

                                var n = r["num"].ToString();
                                sum = Convert.ToString(double.Parse(sum) + double.Parse(r["num"].ToString()));//
                            }
                        }
                        //list[i].barCodeCount = dr.Length.ToString();
                        //list[i].backMark = backCount.ToString();
                        list[i].Add("number", sum);
                        list[i].Add("barCodeCount", dr.Length.ToString());
                    }
                }
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 销售出库记录
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult GetSaleRecords(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }

                sb.Append(" 1=1 and inOutType='pos' and isCount=0 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "sDate")
                            {
                                sb.Append("convert(date,createtime)>='" + obj.Value.ToString() + "' ");
                            }
                            else if (obj.Name == "eDate")
                            {
                                sb.Append("convert(date,createtime)<='" + obj.Value.ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }
                }
                var list = cmd.PageList("V_BarEntoryRecords_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                if (list.Count > 0)
                {
                    string mCodes = "";
                    for (int i = 0; i < list.Count; i++)
                    {
                        mCodes += "'" + list[i]["mCode"].ToString() + "',";
                    }
                    sb.Clear();
                    sb.Append("select barcode,mCode,num from bar_BarEntryRecords_list where status='Y'");
                    sb.Append("and mCode in(" + mCodes.TrimEnd(',') + ")");
                    var lTable = cmd.GetDataTable(sb.ToString());
                    for (int i = 0; i < list.Count; i++)
                    {
                        var dr = lTable.Select("mCode='" + list[i]["mCode"].ToString() + "'");
                        string sum = "0";

                        foreach (DataRow r in dr)
                        {
                            if (r["num"] != null && !string.IsNullOrWhiteSpace(r["num"].ToString()))
                            {
                                //int intResult;
                                //bool success = int.TryParse(r["num"].ToString(), out intResult);

                                var n = r["num"].ToString();
                                sum = Convert.ToString(double.Parse(sum) + double.Parse(r["num"].ToString()));//
                            }
                        }
                        //list[i].barCodeCount = dr.Length.ToString();
                        //list[i].backMark = backCount.ToString();
                        list[i].Add("number", sum);
                        list[i].Add("barCodeCount", dr.Length.ToString());
                    }
                }
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 根据出入库编码查询记录
        /// </summary>
        /// <param name="condition">mCode</param>
        /// <param name="BaseCode">用户账号</param>
        /// <returns></returns>
        public ReturnResult getRecordsListByCode(string condition, string BaseCode)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_BarEntryRecords_list where 1=1 ");
                //sb.Append("  mCode='" + json["mCode"].ToString().Trim() + "'");
                foreach (JProperty key in json.Properties())
                {
                    if (!string.IsNullOrWhiteSpace(key.Value.ToString()))
                    {
                        sb.Append(" and ");
                        if (key.Name.Equals("sDate"))
                        {
                            sb.Append("convert(date,createtime)>='" + key.Value.ToString() + "'");
                        }
                        else if (key.Name.Equals("eDate"))
                        {
                            sb.Append("convert(date,createtime)<='" + key.Value.ToString() + "'");
                        }
                        else
                        {
                            sb.Append("" + key.Name + "='" + key.Value.ToString() + "'");
                        }
                    }
                }
                //var userInfo = LoginInfo();
                //sb.Append(" and baseCode='" + BaseCode + "'");
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 自动填充文本框 输入内容提示
        /// </summary>
        /// <param name="filter">过滤关键字</param>
        /// <param name="field">数据表字段</param>
        /// <param name="sql">带有{替换词}的完整SQL</param>
        /// <returns>自动提示内容列表</returns>
        public ReturnResult Input_AutoComplete(string filter, string field, string sql)
        {
            rsl = new ReturnResult { };

            try
            {
                //sql = $@"select top 10 {field} from fun_Inventory_Info where {field} like '%{filter}%'";

                sql = sql.Replace("{filter}", filter);
                sql = sql.Replace("{field}", field);

                var dt = cmd.GetDataTable(sql);

                //var autoCompleteList = new List<string>();
                var autoCompleteList = from autoCompletes in dt.AsEnumerable()
                                       select autoCompletes.Field<string>(field);

                rsl.Result = true;
                rsl.Data = autoCompleteList;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }

        // 获取存货信息
        public ReturnResult InvInfo(string invStr)
        {
            rsl = new ReturnResult { };
            try
            {
                var inv = JsonConvert.DeserializeObject<DbInventory>(invStr);
                var list = cmd.GetDataByObject<DbInventory>(inv);

                rsl.Result = true;
                rsl.Data = list[0];
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        // 
        /// <summary>
        /// 获取生产打码列表
        /// </summary>
        /// <param name="loginUser"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getProBarPrintList(JObject loginUser, string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }

                StringBuilder sb = new StringBuilder();
                sb.Append(" 1=1 and status in ('ps-doing','ps-finish') ");
                string userCode = "", isAdmin = "";
                //获取登录人员权限信息
                userCode = loginUser["userCode"].ToString();
                isAdmin = loginUser["isAdmin"].ToString();
                if (isAdmin == "0")
                {//非管理员只显示关联工序数据
                    sb.Append(" and gxCode in (select GongXu from pi_GongXuUser_set where usCode='" + userCode + "') ");
                }
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                foreach (var obj in json)
                {
                    if (obj.Value != null && !string.IsNullOrWhiteSpace(obj.Value.ToString()))
                    {
                        if (obj.Key == "gxStatus")
                        {
                            continue;
                        }
                        else
                        {
                            sb.Append(" and " + obj.Key.ToString().Trim() + " like '%" + obj.Value.ToString().Trim() + "%'");
                        }
                    }
                }
                if (json.Property("gxStatus") != null && !string.IsNullOrWhiteSpace(json["gxStatus"].ToString()))
                {
                    sb.Append(" and isFinish='" + json["gxStatus"].ToString() + "'");
                }

                

                var tableName = "V_plan_print";
                var list = cmd.PageList(tableName, pageIndex, pageSize, sb.ToString(), "plCode desc,gxOrder", ref pageCount);
                this.GetGongXuNumber(ref list);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取工序生产数
        /// </summary>
        /// <param name="list"></param>
        private void GetGongXuNumber(ref List<Dictionary<string, string>> list)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.Count; i++)
            {
                string gxCode = list[i]["gxCode"];
                string plCode = list[i]["plCode"];
                sb.Clear();
                sb.Append("select top 1 fieldValue from pi_ProductionPlan_gy where plCode='" + plCode + "'");
                sb.Append(" and gxCode='" + gxCode + "' and isdel=0 and fieldCode='gxNum'");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0 && !string.IsNullOrWhiteSpace(table.Rows[0]["fieldValue"].ToString()))
                {
                    list[i]["gxNumber"] = table.Rows[0]["fieldValue"].ToString();
                }
                else
                {
                    list[i]["gxNumber"] = "0";
                }
            }
        }

        public ReturnResult getPurchasePrintList(JObject loginUser, string pageIndex, string pageSize, ref string pageCount, string condition, string sign = null)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }

                StringBuilder sb = new StringBuilder();
                string userCode = "", isAdmin = "", roleCode = "";
                #region 人员身份信息
                //获取登录人员权限信息
                userCode = loginUser["userCode"].ToString();
                isAdmin = loginUser["isAdmin"].ToString();
                roleCode = loginUser["powerRole"].ToString();

                #endregion

                #region 检索条件

                //按大类 筛选
                var sql = "select * from sys_parameters_info where parCode='cgShowPro' and enable='open' and isDel=0";
                var values = "";
                var table = cmd.GetDataTable(sql);
                if (table.Rows.Count > 0)
                {
                    values = table.Rows[0]["parValue"].ToString();
                }
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if ((obj.Name == "status" && json["cStatus"] != null) || obj.Name == "switch")
                            {
                                continue;
                            }
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "cStatus")
                            {
                                var sArr = obj.Value.ToString().Split(',');
                                string status = "";
                                foreach (string s in sArr)
                                {
                                    if (!string.IsNullOrWhiteSpace(s))
                                    {
                                        status += "'" + s + "',";
                                    }
                                }
                                sb.Append("status in (" + status.TrimEnd(',') + ")");
                            }
                            else if (obj.Name == "sDate")
                            {
                                sb.Append(" convert(datetime,createtime, 20)" + " >='" + obj.Value.ToString() + "' ");
                            }
                            else if (obj.Name == "eDate")
                            {//结束时间
                                sb.Append(" convert(date,createtime, 20)" + "<= '" + obj.Value.ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }
                }

                if(!string.IsNullOrEmpty(values))
                {
                    if(!string.IsNullOrEmpty(sb.ToString()))
                        sb.Append(" and ");
                    sb.Append(" (");
                    for(var i=0;i<values.Split(',').Length;i++)
                    {
                        if (i > 0)
                        {
                            sb.Append(" or ");
                        }
                        sb.Append(" cInvCCode like '" + values.Split(',')[i] + "%' ");
                    }
                    sb.Append(") ");
                }

                #endregion

                var tableName = "V_U8_PurchasePrint";

                var list = cmd.PageList(tableName, pageIndex, pageSize, sb.ToString(), "cCode desc", ref pageCount);

                //手动将入库日期后面的时间（00:00:00）去掉
                foreach (var s in list)
                {
                    //s["dDate"] = s["dDate"].ToString().Substring(0, 10);
                    s["dDate"] = Convert.ToDateTime(s["dDate"].ToString()).ToString("yyyy-MM-dd HH:mm:ss").Substring(0, 10);
                }

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        // 获取存货筛选列表
        public List<FilteredProduct> GetProductList(string json)
        {
            var list = new List<FilteredProduct>();
            try
            {
                var queryDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                var proCode = queryDic["proCode"];
                var proName = queryDic["proName"];
                var spec = queryDic["spec"];
                var baseCode = queryDic["baseCode"];

                var sql = $@"select top 100 proCode,proName,spec from fun_Inventory_Info 
where proCode like '%{proCode}%' and proName like '%{proName}%' and spec like '%{spec}%' and baseCode = '{baseCode}' ;";

                var dt = cmd.GetDataTable(sql);

                list = cmd.TableTolist<FilteredProduct>(dt);
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return list;
        }

        // 获取仓库列表

        /// <summary>
        /// 期初条码打印
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public ReturnResult InitPrint(string json)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var queryData = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                var printNumber = int.Parse(queryData["printNumber"]);
                
                var barCodes = this.CreateCodeInfo("QC", "期初编码", "4", printNumber);

                if (barCodes == null) { rsl.Message = "批量条码生成失败"; return rsl; }

                var barCodeList = barCodes.Split(',');

                var bars = new List<DbProductBarCode>();

                var unit = GetUnitByProCode(queryData["proCode"]);

                if (string.IsNullOrEmpty(unit))
                {
                    rsl.Message = "无法获取存货主计量单位";
                    return rsl;
                }

                foreach (var barCode in barCodeList)
                {
                    var number = queryData["proWeight"];
                    if (unit == "kg")
                    {
                        number = queryData["proWeight"];
                    }
                    else
                    {
                        number = queryData["proMeter"];
                    }
                    var bar = new DbProductBarCode
                    {
                        barCode = barCode,
                        barType = "QC",
                        number = number,
                        proCode = queryData["proCode"],
                        proName = queryData["proName"],

                        proWeight = queryData["proWeight"],
                        wareHouse = queryData["houseCode"],
                        proMeter = queryData["proMeter"],

                        cu_iUnitCost = queryData["cu_iUnitCost"],
                        cu_shelfLife = queryData["cu_shelfLife"],
                        cu_shelfLifeUnit = queryData["cu_shelfLifeUnit"],
                        cu_vendor = queryData["cu_vendor"],
                        cu_batch = queryData["cu_batch"],
                        boxCode = queryData["cu_batch"],
                        cu_qualityLevel = queryData["cu_qualityLevel"],
                        memo = queryData["memo"],

                        printNum = number,//初始打印数量

                        status = "Y",
                        isInitial = "Y",
                        barStatus = "need-out",
                        happenDate = queryData["happenDate"],
                        createtime = getNow(),
                        createuser = queryData["userCode"],
                        unit = unit,
                    };

                    bars.Add(bar);

                    oper = new OperateModel();

                    oper.Data = bar;
                    oper.Types = OperateModel.OperateType.Add;

                    operList.Add(oper);
                }

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }

                rsl.Data = barCodes;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        string GetUnitByProCode(string proCode)
        {
            var unit = "";
            try
            {
                var sql = $@"select  sysUnit from fun_Inventory_Info where proCode = '{proCode}' ";
                var dt = cmd.GetDataTable(sql);

                if (dt.Rows.Count > 0)
                {
                    unit = dt.Rows[0]["sysUnit"].ToString();
                }
            }
            catch (Exception ex)
            {
                _log.Error("存货编码获取单位名称报错：");
                _log.Error(ex.Message);
            }
            return unit;
        }

        // tuple.item1
        // 工序处在计划的第几位
        // -1 计划不存在这个工序
        // 0 工序是计划第一道工序
        // i 工序是计划 （i+1） 道工序
        // tuple.item2
        // 当i是正数到时候，上一道工序代码
        // 当i不是正数的时候，空字符串
        Tuple<int, string> GxIndexInPlan(string plCode, string gxCode)
        {
            // 获取计划所有工序，排序，判断当前工序位次
            var gongxuSql = $@"select * from pi_ProductionPlan_gx 
where plCode = '{plCode}' and isdel=0 order by gxOrder asc; ";
            var gongxuDt = cmd.GetDataTable(gongxuSql);

            // 当前工序的位次
            int i = 0;
            for (; i < gongxuDt.Rows.Count; i++)
            {
                var row = gongxuDt.Rows[i];
                if (row["gxCode"].ToString() == gxCode)
                {
                    break;
                }
                if (i == (gongxuDt.Rows.Count - 1))
                {
                    i = -1;
                    break;
                }
            }

            var lastGx = "";

            if (i != 0 && i != -1)
            {
                var p = i - 1;
                lastGx = gongxuDt.Rows[p]["gxCode"].ToString();
            }

            return new Tuple<int, string>(i, lastGx);
        }

        // 判断工序是否为计划的最后一道工序
        public bool IsFinalStep(string json)
        {
            var queryDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

            var gxCode = queryDic["gxCode"];
            var plCode = queryDic["plCode"];

            var gongxuSql = $@"select * from pi_ProductionPlan_gx 
where plCode = '{plCode}' and isdel=0 order by gxOrder desc; ";


            try
            {
                var gongxuDt = cmd.GetDataTable(gongxuSql);

                var firstGxCode = gongxuDt.Rows[0]["gxCode"].ToString();

                if (firstGxCode == gxCode)
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                _log.Info("IsFinalStep报错：" + ex.Message);
            }
            return false;
        }
        // 根据生产计划编码 获取执行标准
        public string getZhxbz(string json)
        {
            var queryDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

            var plCode = queryDic["plCode"];

            var bzSql = $@"select cName zhxbz from fun_CommonData_info where parentCode='zhxBz' and isdel=0 and cCode in ( select zhxbz from pi_ProductionPlan_info where plCode = '{plCode}'); ";

            try
            {
                var bzDt = cmd.GetDataTable(bzSql);
                var bz = bzDt.Rows[0]["zhxbz"].ToString();

                return bz;
            }
            catch (Exception ex)
            {
                _log.Info("getZhxbz报错：" + ex.Message);
            }
            return "";
        }
        // 根据生产计划编码 获取材质
        public string getCuCaiZhi(string json)
        {
            var queryDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

            var plCode = queryDic["plCode"];

            var bzSql = $@"select cName cu_caizhi from fun_CommonData_info where parentCode='caizhi' and isdel=0 and cCode in (select cu_caizhi from pi_ProductionPlan_info where plCode = '{plCode}' ) ; ";

            try
            {
                var czDt = cmd.GetDataTable(bzSql);
                var cz = czDt.Rows[0]["cu_caizhi"].ToString();

                return cz;
            }
            catch (Exception ex)
            {
                _log.Info("getCuCaiZhi报错：" + ex.Message);
            }
            return "";
        }

        /// <summary>
        /// 获取关联条码
        /// </summary>
        /// <param name="index"></param>
        /// <param name="lastGx"></param>
        /// <param name="plCode"></param>
        /// <param name="msg"></param>
        /// <param name="spec"></param>
        /// <param name="gxCode"></param>
        /// <returns></returns>
        public DataTable getRealtionBars(int index, string lastGx, string plCode, ref string msg, string spec = null, string gxCode = null)
        {
            var table = new DataTable();
            try
            {
                // 获取车间库编码
                var work_sql = "select parValue from sys_parameters_info where parCode = 'work_warehouse_code' ";
                //var workCode = cmd.GetDataTable(work_sql).Rows[0]["parValue"].ToString();
                #region 多个仓库（Ning）
                var workCode = "";
                var ware = cmd.GetDataTable(work_sql).Rows[0]["parValue"].ToString();
                var list = ware.Split(',');
                for (int i = 0; i < list.Length; i++)
                {
                    workCode += "'" + list[i].ToString() + "',";
                }
                workCode = workCode.TrimEnd(',');
                #endregion
                StringBuilder sb = new StringBuilder();
                if (index != 0)
                {
                    #region 非第一道工序
                    sb.Append("select bar.barCode,bar.proName, bar.proWeight,bar.proMeter,bar.cu_iUnitCost,");
                    sb.Append("bar.cu_batch,bar.spec,bar.number,bar.gxName,bar.createtime,bar.gxCode,bar.gxCode zyGxCode,bar.proCode ");
                    sb.Append("from V_BarCode_Info bar where bar.planCode='" + plCode + "' ");// and gxCode='" + lastGx + "' 
                    sb.Append("and bar.barStatus not in ('bar-drop','used-finish','need-check') and CONVERT(decimal(18,2),bar.number)>0  ");
                    sb.Append("and gxCode!='CPFQ'  ");  //24.12.05新增    成品分切工序切出来的是成品，不再用作关联条码
                    sb.Append("union ");
                    #endregion
                }
                #region 计划占用条码
                sb.Append("select bar.barCode,bar.proName, bar.proWeight,bar.proMeter,bar.cu_iUnitCost,");
                sb.Append("bar.cu_batch,bar.spec,bar.number,bar.gxName,bar.createtime,bar.gxCode,mat.gxCode zyGxCode,bar.proCode ");
                sb.Append("from pi_ProductsOccupation_list mat ");
                sb.Append("inner join V_BarCode_Info bar on mat.barCode = bar.barCode ");
                //sb.Append("where mat.isdel=0 and mat.plCode = '" + plCode + "'  and bar.warehouse = '" + workCode + "' ");
                sb.Append("where mat.isdel=0 and mat.plCode = '" + plCode + "'  and bar.warehouse in (" + workCode + ") ");
                sb.Append("and bar.barStatus not in ('bar-drop','used-finish') and  mat.status='Y' and CONVERT(decimal(18,2),bar.number)>0 ");
                //if (!string.IsNullOrWhiteSpace(spec))
                //{
                //    sb.Append(" and bar.spec='" + spec + "'");
                //}
                table = cmd.GetDataTable(sb.ToString());
                #endregion
                if (index == 0)
                {
                    if (!string.IsNullOrWhiteSpace(gxCode))
                    {
                        var temTable = table.Clone();
                        foreach (DataRow r in table.Rows)
                        {
                            var gxCodes = r["zyGxCode"].ToString().Split(',');
                            foreach (string s in gxCodes)
                            {
                                if (!string.IsNullOrWhiteSpace(s) && s == gxCode)
                                {
                                    temTable.Rows.Add(r.ItemArray);
                                    break;
                                }
                            }
                        }
                        return temTable;
                    }

                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }

            return table;
        }



        public List<Dictionary<string, string>> GetRelativeBarCodes(string json)
        {
            var list = new List<RelativeBarCode>();
            try
            {
                var jObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                var plCode = jObj["plCode"];
                var gxCode = jObj["gxCode"];

                // 判断工序是计划的第几道
                var tuple = GxIndexInPlan(plCode, gxCode);

                var i = tuple.Item1;
                var lastGx = tuple.Item2;

                #region 已注释
                // 如果该工序是计划的第一道工序
                // 占用表pi_ProductsOccupation_list
                //                if (i == 0)
                //                {
                //                    // 获取车间库编码
                //                    var work_sql = "select parValue from sys_parameters_info where parCode = 'work_warehouse_code' ";
                //                    var workCode = cmd.GetDataTable(work_sql).Rows[0]["parValue"].ToString();

                //                    var occuSql = $@"select mat.*,mat.barCode as barCode,inv.proName, bar.proWeight as weight, 
                //bar.proMeter as meter, bar.cu_iUnitCost, bar.cu_batch,
                //inv.spec,bar.number,gx.cName as gxName,bar.createtime
                //from pi_ProductsOccupation_list mat 
                //left join fun_Inventory_Info inv  on mat.proCode = inv.proCode
                //left join bar_ProductBarCode_info bar on mat.barCode = bar.barCode
                //left join [fun_CommonData_info] gx on bar.gxCode = gx.cCode

                //where mat.plCode = '{plCode}' and mat.barCode is not null 
                //and bar.barStatus != 'bar-drop' 
                //and ( ( bar.barStatus == 'need-out' and bar.warehouse == '{workCode}' ) or bar.barStatus != 'needOut' ) ";
                //                    //and bar.barStatus not in ('need-out','bar-drop','bar-used') ";
                //                    var occuDt = cmd.GetDataTable(occuSql);

                //                    list = cmd.TableTolist<RelativeBarCode>(occuDt);
                //                }
                //                // 如果不是第一道工序
                //                else
                //                {
                //                    var lastGx = tuple.Item2;

                //                    var lastGxBarCodesql = $@"select bar.barcode,bar.procode,bar.proname,bar.number as weight,bar.proMeter as meter,
                //inv.spec,bar.number,gx.cName as gxName,bar.createtime, bar.cu_iUnitCost, bar.cu_batch
                //from bar_ProductBarCode_info bar 
                // left join fun_Inventory_Info inv on bar.proCode = inv.proCode
                //left join [fun_CommonData_info] gx on bar.gxCode = gx.cCode
                //where bar.planCode = '{plCode}' and bar.gxCode = '{lastGx}' and bar.status = 'Y' and bar.barStatus not in ('need-out','bar-drop','used-finish','need-check')";

                //                    var lastGxBarCodeDt = cmd.GetDataTable(lastGxBarCodesql);

                //                    list = cmd.TableTolist<RelativeBarCode>(lastGxBarCodeDt);
                //                }

                #endregion

                string msg = "";
                var table = this.getRealtionBars(i, lastGx, plCode, ref msg, null, gxCode);

                if (!string.IsNullOrEmpty(msg))
                {
                    return null;
                }

                return cmd.TableToDictionary(table);
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
            return null;
        }

        public RelativeBarCode GetScannedBarCodeInfo(string json)
        {
            var bar = new RelativeBarCode();
            try
            {
                var jObj = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                var barCode = jObj["barCode"];
                var plCode = jObj["plCode"];
                var gxCode = jObj["gxCode"];

                // 判断工序是计划的第几道
                var tuple = GxIndexInPlan(plCode, gxCode);

                var i = tuple.Item1;
                var lastGx = tuple.Item2;

                string msg = "";

                var table = this.getRealtionBars(i, lastGx, plCode, ref msg, null, gxCode);

                if (!string.IsNullOrEmpty(msg))
                {
                    return null;
                }
                var list = cmd.TableTolist<RelativeBarCode>(table);


                foreach (var reBar in list)
                {
                    if (reBar.barCode == barCode)
                    {
                        bar = reBar;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
            return bar;
        }

        /// <summary>
        /// 条码打印方法
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult SaveBarcodes(string datas)
        {

            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(datas);

                if (json["barType"].ToString() == "SC")
                {
                    this.ProductsPlanPrint(datas);
                }
                else if (json["barType"].ToString() == "QC")
                {
                    this.InitPrint(datas);
                }
                else if (json["barType"].ToString() == "CG")
                {
                    this.PurchaseInPrint(datas);
                }
                else
                {
                    rsl.Message = "未知条码类型，服务无法生成标识码";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 生产计划打码方法
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        private ReturnResult ProductsPlanPrint(string datas)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                StringBuilder sb = new StringBuilder();
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                #region 验证计划工序是否完成
                sb.Append("select id,isnull(startTime,'') startTime,isFinish from pi_ProductionPlan_gx where ");
                sb.Append(" plCode='" + json["plCode"].ToString() + "' and gxCode='" + json["gxCode"].ToString() + "' and isdel=0");
                var xTable = cmd.GetDataTable(sb.ToString());
                if (xTable.Rows.Count < 1)
                {
                    rsl.Message = "没有查询到关联工序"; return rsl;
                }
                else
                {
                    if (xTable.Rows[0]["isFinish"].ToString() == "1")
                    {
                        rsl.Message = "工序已完成，禁止再生产"; return rsl;
                    }
                    if (string.IsNullOrWhiteSpace(xTable.Rows[0]["startTime"].ToString()))
                    {
                        DbPlanGx gx = new DbPlanGx();
                        gx.id = int.Parse(xTable.Rows[0]["id"].ToString());
                        gx.startTime = getNow();
                        oper = new OperateModel();
                        oper.Conditions = "id";
                        oper.Data = gx;
                        oper.Types = OperateModel.OperateType.Edit;
                        operList.Add(oper);
                    }
                }
                #endregion

                string bomCode = "";
                if (json["gxCode"].ToString() == "FQ"  || json["gxCode"].ToString().Contains("FQ"))
                {
                    rsl = this.FenQieBarCodePrint(datas);
                }
                else
                {
                    #region 非分切工序打码
                    int printNum = 1;
                    if (json.Property("printNumer") != null && !string.IsNullOrWhiteSpace(json["printNumer"].ToString()))
                    {
                        printNum = int.Parse(json["printNumer"].ToString());
                    }
                    string erpRowId = "", erpCode = "", cuName = "",planPro="";
                    string hDate = getNowDate();
                    if (json.Property("happenDate") != null && !string.IsNullOrWhiteSpace(json["happenDate"].ToString()))
                    {
                        hDate = DateTime.Parse(json["happenDate"].ToString()).ToString("yyyy-MM-dd");
                    }
                    string barCodes = CreateBarCodeXR("XR", "生产打码", "4", hDate, printNum);
                    #region 获取计划关联ERP单据信息  和存货信息
                    sb.Clear();
                    sb.Append("select isnull(erpOrder,'') erpOrder,isnull(erpRowId,'') erpRowId,cuName,isnull(bomCode,'') bomCode,proCode ");
                    sb.Append(" from pi_ProductionPlan_info where plCode = '" + json["plCode"] + "'");
                    var plTable = cmd.GetDataTable(sb.ToString());
                    if (plTable.Rows.Count > 0)
                    {
                        erpCode = plTable.Rows[0]["erpOrder"].ToString();
                        erpRowId = plTable.Rows[0]["erpRowId"].ToString();
                        cuName = plTable.Rows[0]["cuName"].ToString();
                        bomCode= plTable.Rows[0]["bomCode"].ToString();
                        planPro = plTable.Rows[0]["proCode"].ToString();
                    }
                    #endregion
                    if (barCodes == null)
                    {
                        rsl.Message = "打印条码生成失败";
                        return rsl;
                    }
                    sb.Clear();
                    sb.Append("select top 1 sysUnit from fun_Inventory_info where proCode = '" + json["proCode"].ToString() + "'");
                    var unitTable = cmd.GetDataTable(sb.ToString());
                    string sysUnit = "kg";
                    if (unitTable.Rows.Count > 0)
                    {
                        sysUnit = unitTable.Rows[0]["sysUnit"].ToString();
                    }
                    var bArr = barCodes.Split(',');

                    List<Dictionary<string, object>> mlist = new List<Dictionary<string, object>>();
                    string reBars = "";
                    double barPrice = 0;//条码单价 
                    var code = getTimeString();//操作编码

                    if (json.Property("relationBar") != null && !string.IsNullOrWhiteSpace(json["relationBar"].ToString()))
                    {
                        //关联条码处理
                        mlist = this.ReBarDo(json["relationBar"].ToString(), json["plCode"].ToString(),code, ref operList, ref reBars,ref barPrice);
                    }

                    DbProductBarCode bar;
                    DbBarPrintLogs bp;
                    var barJson = JsonConvert.DeserializeObject<List<JObject>>(json["relationBar"].ToString());

                    #region 循环构建条码
                    //成品的话，加上手填的计划用料（即无码的）
                    if (planPro== json["proCode"].ToString())
                    {
                        sb.Clear();
                        sb.Append("seleCt * from pi_PlanMaterial_list where plCode='" + json["plCode"].ToString() + "' and reBarCode is null");
                        var pmTable = cmd.GetDataTable(sb.ToString());
                        if (pmTable.Rows.Count > 0)
                        {
                            foreach (DataRow dr in pmTable.Rows)
                            {
                                barPrice += double.Parse(dr["total"].ToString());
                            }
                        }
                    }
                    
                    barPrice = barPrice / bArr.Length;   //条码总价

                    foreach (var b in bArr)
                    {
                        if (!string.IsNullOrWhiteSpace(b))
                        {
                            var temp = JsonConvert.DeserializeObject<Dictionary<string, object>>(datas);
                            temp["relationBar"] = reBars;
                            bar = JsonConvert.DeserializeObject<DbProductBarCode>(JsonConvert.SerializeObject(temp));
                            bar.planCode = json["plCode"].ToString();
                            if (json.Property("isCheck") != null && json["isCheck"].ToString() == "1")
                            {
                                bar.barStatus = "need-check";//复合工序条码需要进行检验
                            }
                            else
                            {
                                bar.barStatus = "need-in";
                            }
                            if (json.Property("machine") != null && !string.IsNullOrWhiteSpace(json["machine"].ToString()))
                            {
                                bar.machine = json["machine"].ToString();
                            }
                            bar.relationBar = reBars;
                            bar.barCode = b;
                            bar.U8relationCode = erpCode;
                            bar.isInitial = "N";
                            bar.erpRowNo = erpRowId;
                            bar.status = "Y";
                            bar.happenDate = hDate;
                            bar.unit = sysUnit;
                            if (bar.unit == "kg")
                            {
                                bar.number = bar.proWeight;
                            }
                            else
                            {
                                bar.number = bar.proMeter;
                            }

                            bar.printNum = bar.number;  //初始打印数量

                            if (!string.IsNullOrWhiteSpace(bar.planCode))
                            {
                                bar.costPlan = bar.planCode;
                                bar.cu_iUnitCost = (barPrice / double.Parse(bar.number)).ToString("0.000");
                            }
                            bar.createtime = getNow();

                            if(bar.cu_inspector== "[请选择检验人员]")
                            {
                                bar.cu_inspector = "";
                            }
                            
                            var proCode = bar.proCode;

                            // 避免为空报错
                            try
                            {
                                bar.cu_shelfLife = json["cu_shelfLife"].ToString();//保质期
                                if(json["cu_material"]!=null)
                                    bar.cu_material = json["cu_material"].ToString();//材质
                                bar.cu_inspector = json["cu_inspector"].ToString();//检验员
                                bar.cu_qualityLevel = json["cu_qualityLevel"].ToString();  //质量等级
                            }
                            catch (Exception ex)
                            {
                                rsl.Message = "请检查是否填写完整";
                                return rsl;
                            }

                            bar.boxCode = bar.cu_batch;

                            oper = new OperateModel();
                            oper.Data = bar;
                            oper.Types = OperateModel.OperateType.Add;
                            operList.Add(oper);

                            foreach (var rb in barJson)
                            {
                                #region 添加打印记录 
                                bp = new DbBarPrintLogs();
                                bp.newBar = b;
                                bp.weight = double.Parse(bar.proWeight).ToString("0.00");
                                bp.meter = double.Parse(bar.proMeter).ToString("0.00");
                                bp.oldBar = rb["barCode"].ToString();
                                bp.useWeight = (double.Parse(rb["useWeight"].ToString()) / bArr.Length).ToString("0.00");
                                bp.useMeter = (double.Parse(rb["useMeter"].ToString()) / bArr.Length).ToString("0.00");
                                bp.mCode = code;
                                oper = new OperateModel();
                                oper.Data = bp;
                                oper.Types = OperateModel.OperateType.Add;
                                operList.Add(oper);
                                #endregion
                            }
                        }

                    }
                    #endregion

                    #region 关联版辊
                    if (!string.IsNullOrWhiteSpace(bomCode) && json["gxCode"].ToString() == "YS")
                    {
                        sb.Clear();
                        sb.Append("select * from fun_BanYang_list where byBarCode in(select materialCode from bom_ProductionBom_sub ");
                        sb.Append("where bomCode='" + bomCode + "')");
                        var byTable = cmd.GetDataTable(sb.ToString());
                        if (byTable.Rows.Count > 0 && byTable.Rows[0]["status"].ToString() == "need-out")
                        {
                            if (byTable.Rows[0]["PPlan"] == null || string.IsNullOrWhiteSpace(byTable.Rows[0]["PPlan"].ToString()))
                            {
                                rsl.Message = "请先将版辊进行出库：" + byTable.Rows[0]["byBarCode"].ToString();
                                rsl.Result = false;
                                return rsl;
                            }

                            #region 版辊出库记录
                            #region 构建参数
                            string tempbarCodes = "";
                            List<string> barList = new List<string>();  //版辊编码
                            List<DbTempScanData> qList = new List<DbTempScanData>();
                            DbTempScanData temp;
                            foreach (DataRow dr in byTable.Rows)
                            {
                                barList.Add(dr["byBarCode"].ToString());
                                temp = new DbTempScanData();
                                temp.happenDate = getNowDate();
                                temp.wareHouse = dr["wareHouse"].ToString();
                                temp.isBlue = "1";
                                temp.createuser = json["userCode"].ToString();
                                temp.typeCode = "";//U8出入库类别
                                temp.operateDept = "";  //操作部门
                                temp.outOrderCode = ""; //关联的U8单据号
                                temp.barCode = dr["byBarCode"].ToString();
                                temp.memo = "版辊非第一次印刷，打码时手动出库";
                                temp.operateType = "02";
                                qList.Add(temp);
                            }

                            var cCode = getTimeString();//单据的临时编码
                            Dictionary<string, object> tempdic = new Dictionary<string, object>();
                            tempdic.Add("mCode", cCode);//临时编码
                            tempdic.Add("inOutType", "pobg");  //版辊出库
                            tempdic.Add("type", "pobg");
                            tempdic.Add("outOrderCode", "");//U8单号
                            tempdic.Add("baseCode", "");
                            tempdic.Add("barList", barList);


                            #endregion

                            #region 添加主表和子表出入库记录    修改条码状态，添加计划用料信息
                            ServiceBLL service = new ServiceBLL();
                            service.insertMain(tempdic, qList, ref operList,"PC");
                            rsl = service.insertList(tempdic, qList, ref operList, ref tempbarCodes, null);
                            if (!rsl.Result)
                            {
                                return rsl;
                            }
                            #endregion

                            #endregion
                        }
                    }


                    #endregion

                    #region 生成材料出库单
                    if (mlist.Count > 0)
                    {
                        #region 构建参数

                        #region 获取材料出库默认的 业务类型 、部门  、仓库
                        sb.Clear();
                        sb.Append("seleCt parValue,parCode from sys_parameters_info where parCode like '%Style' and isdel=0 ");
                        var table = cmd.GetDataTable(sb.ToString());

                        var crdcode = "22"; //旭日环境
                        //crdcode = table.Rows[0][0].ToString();
                        crdcode = table.Select("parCode='pom_Rd_Style'")[0]["parValue"].ToString();

                        var dept = "5"; //旭日：3 生产部  5 库存部   本地 ：5 二车间
                        dept = table.Select("parCode='all_Dept_Style'")[0]["parValue"].ToString();

                        var wareHouse = "8";  //旭日:车间库
                        //wareHouse = table.Select("parCode='pom_Ware_Style'")[0]["parValue"].ToString();
                        //条码在哪取那
                        #region 查询条码库存（Ning）客户说不会出现多个仓库
                        var bs = reBars.Split(',');
                        var Bars = "";
                        for (int i = 0; i < bs.Length; i++)
                        {
                            Bars += "'" + bs[i].ToString() + "',";
                        }
                        Bars = Bars.TrimEnd(',');
                        sb.Clear();
                        sb.Append(" select wareHouse from bar_ProductBarCode_info where barCode in (" + Bars + ") ");
                        sb.Append(" group by wareHouse order by wareHouse desc ");
                        var wTable = cmd.GetDataTable(sb.ToString());
                        int wnum = 0;
                        foreach (DataRow r in wTable.Rows)
                        {
                            if (!string.IsNullOrWhiteSpace(r["wareHouse"].ToString()))
                            {
                                wareHouse = r["wareHouse"].ToString();
                                wnum++;
                            }
                        }
                        if (wnum > 1)
                        {
                            rsl.Message = "关联条码存在多个仓库！";
                            return rsl;
                        }
                        #endregion
                        #endregion

                        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                        Dictionary<string, string> dic;
                        foreach (var s in mlist)
                        {
                            dic = new Dictionary<string, string>();
                            dic["proCode"] = s["proCode"].ToString();
                            dic["proName"] = "";
                            dic["number"] = s["number"].ToString();
                            dic["cu_batch"] = s["batch"].ToString();
                            dic["iunitcost"] = s["uPrice"].ToString();//单价

                            dic["plCode"] = json["plCode"].ToString();//计划号

                            var total = decimal.Parse(s["uPrice"].ToString()) * decimal.Parse(s["number"].ToString());
                            dic["iprice"] = total.ToString();//总金额

                            list.Add(dic);
                        }

                        List<string> bars = new List<string>();
                        bars.Add(reBars);//出库条码

                        var baseCode = json["baseCode"].ToString();
                        var userCode = json["userCode"].ToString();

                        #endregion

                        U8Order order = new U8Order();
                        rsl = order.tyInOut(list, bars, wareHouse, crdcode, dept, baseCode, userCode, "MaterialOut");

                        var U8Codes = string.Empty;
                        var U8Message = string.Empty;
                        var errBarCodes = new List<string>();//调用接口失败的条码

                        if (rsl.Result)
                        {
                            if (rsl.Data != null)
                            {
                                List<InOutResult> iorList = new List<InOutResult>();
                                iorList = (List<InOutResult>)rsl.Data;
                                if (iorList.Count > 0)
                                {
                                    U8Codes = "";
                                    foreach (InOutResult ior in iorList)
                                    {
                                        if (!string.IsNullOrWhiteSpace(ior.SuccOrderCode))
                                        {
                                            #region 调用接口成功
                                            U8Codes += ior.SuccOrderCode + ",";

                                            #region 返回错误信息和错误条码
                                            ErrorResult err = (ErrorResult)ior.ErrorInfo;
                                            if (err != null)
                                            {
                                                if (!string.IsNullOrWhiteSpace(err.ErrorMsg))
                                                {
                                                    U8Message += JsonConvert.SerializeObject(err.BarCodes) + "：" + err.ErrorMsg + "\n";//U8返回来的错误信息
                                                }
                                            }
                                            #endregion

                                            #endregion

                                        }
                                        else
                                        {
                                            #region 返回错误信息和错误条码
                                            ErrorResult err = (ErrorResult)ior.ErrorInfo;
                                            if (err != null)
                                            {
                                                if (!string.IsNullOrWhiteSpace(err.ErrorMsg))
                                                {
                                                    U8Message += JsonConvert.SerializeObject(err.BarCodes) + "：" + err.ErrorMsg + "\n";//U8返回来的错误信息
                                                }
                                                if (err.BarCodes != null && err.BarCodes.Count > 0)
                                                {
                                                    errBarCodes.AddRange(err.BarCodes);
                                                }
                                            }
                                            #endregion
                                        }

                                    }
                                }
                            }
                            if (!string.IsNullOrWhiteSpace(U8Message))
                            {
                                U8Message = "U8接口错误：" + U8Message;
                                rsl.Message = U8Message;
                                rsl.Result = false;
                                return rsl;
                            }

                            _log.Info("(ProductsPlanPrint)打码时条码材料出库成功，单号为：" + U8Codes.TrimEnd(','));
                        }
                        else
                        {
                            rsl.Message = rsl.Message;
                            rsl.Result = false;
                            _log.Info("(ProductsPlanPrint)打码时条码材料出库失败：" + rsl.Message);
                            return rsl;
                        }
                    }
                    #endregion

                    if (operList.Count > 0)
                    {
                        rsl = cmd.MoreUpdate(operList);
                    }
                    else
                    {
                        rsl.Message = "没有提交数据";
                    }
                    if (rsl.Result)
                    {
                        rsl.Data = barCodes;
                    }
                    #endregion
                }


            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 关联条码处理
        /// </summary>
        /// <param name="barCode">关联条码</param>
        /// <param name="operList"></param>
        private List<Dictionary<string, object>> ReBarDo(string barInfo, string plCode,string code, ref List<OperateModel> operList, ref string reBarCodes,ref double barPrice)
        {
            reBarCodes = "";
            var barJson = JsonConvert.DeserializeObject<List<JObject>>(barInfo);
            List<Dictionary<string, object>> mlist = new List<Dictionary<string, object>>();
            double proWeight = 0, proMeter = 0;
            DbProductBarCode bar;
            Dictionary<string, object> mdic;
            DBPlanYongLiao material;
            
            foreach (var b in barJson)
            {
                string sql = "select top 1 sysUnit from fun_Inventory_info where proCode = '" + b["proCode"].ToString() + "'";
                var unitTable = cmd.GetDataTable(sql);
                string sysUnit = "kg";
                if (unitTable.Rows.Count > 0)
                {
                    sysUnit = unitTable.Rows[0]["sysUnit"].ToString();
                }

                #region 查计划 关联条码的占用数量，如果使用数量>=占用数量，则作废该计划对关联条码的占用
                sql = "select * from pi_ProductsOccupation_list where  plCode='" + plCode + "' and barCode= '" + b["barCode"].ToString() + "' and isdel=0 and status='Y' ";
                var zyTable = cmd.GetDataTable(sql);
                var zyNum = "0";//占用数量
                var useNum = "0"; //实际使用数量
                string id = "";
                if (zyTable.Rows.Count > 0)
                {
                    zyNum = zyTable.Rows[0]["number"].ToString();
                    id = zyTable.Rows[0]["id"].ToString();
                }
                if (sysUnit == "kg")
                {
                    useNum = b["useWeight"].ToString();
                }
                else
                {
                    useNum = b["useMeter"].ToString();
                }

                if (decimal.Parse(zyNum) !=0 && decimal.Parse(useNum)>= decimal.Parse(zyNum))
                {
                    DbProductsOccupation oc = new DbProductsOccupation();
                    oc.id = Convert.ToInt32(id);
                    oc.status = "N";
                    oper = new OperateModel();
                    oper.Data = oc;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    operList.Add(oper);
                }


                #endregion

                sql = "select isnull(cu_batch,'') batch,isnull(cu_iUnitCost,'') uCost,costPlan,barStatus,proCode from bar_ProductBarCode_info where barCode='" + b["barCode"].ToString() + "'";
                var barTable = cmd.GetDataTable(sql);
                string batch = "", uCost = "0", barStatus = "", barProCode = "";
                if (barTable.Rows.Count > 0)
                {
                    barStatus = barTable.Rows[0]["barStatus"].ToString();
                    barProCode = barTable.Rows[0]["proCode"].ToString();
                    if (!string.IsNullOrWhiteSpace(barTable.Rows[0]["batch"].ToString()))
                    {
                        batch = barTable.Rows[0]["batch"].ToString();
                    }
                    if (!string.IsNullOrWhiteSpace(barTable.Rows[0]["uCost"].ToString()))
                    {
                        uCost = barTable.Rows[0]["uCost"].ToString();
                    }
                }

                //如果条码在库(barStatus=need-out)  才生成材料出库单
                #region 材料出库单信息
                if (barStatus == "need-out")
                {
                    bool isAdd = true;
                    for (int i = 0; i < mlist.Count; i++)
                    {
                        if (mlist[i]["proCode"].ToString() == b["proCode"].ToString() && mlist[i]["batch"].ToString() == batch)
                        {
                            isAdd = false;
                            if (sysUnit == "kg")
                            {
                                mlist[i]["number"] = (double.Parse(mlist[i]["number"].ToString()) + double.Parse(b["useWeight"].ToString())).ToString("0.000");
                            }
                            else
                            {
                                mlist[i]["number"] = (double.Parse(mlist[i]["number"].ToString()) + double.Parse(b["useMeter"].ToString())).ToString("0.000");
                            }
                            break;
                        }
                    }
                    if (isAdd)
                    {

                        mdic = new Dictionary<string, object>();
                        mdic["proCode"] = barProCode;
                        mdic["batch"] = batch;
                        //mdic["uPrice"] = barTable.Rows[0]["uCost"].ToString();
                        mdic["uPrice"] = uCost;
                        if (sysUnit == "kg")
                        {
                            mdic["number"] = double.Parse(b["useWeight"].ToString());
                        }
                        else
                        {
                            mdic["number"] = double.Parse(b["useMeter"].ToString());
                        }
                        mlist.Add(mdic);

                    }

                    #region 新增计划用料
                    material = new DBPlanYongLiao();
                    if (sysUnit == "kg")
                    {
                        material.number = b["useWeight"].ToString();
                    }
                    else
                    {
                        material.number = b["useMeter"].ToString();
                    }
                    material.reBarCode = b["barCode"].ToString();
                    material.proCode = b["proCode"].ToString();
                    material.uPrice = uCost;
                    material.batch = barTable.Rows[0]["batch"].ToString();
                    material.total = (double.Parse(material.number) * double.Parse(material.uPrice)).ToString("0.000");
                    material.plCode = plCode;
                    material.valueType = "1";
                    material.mType = "ymyl";
                    material.mCode = code;
                    oper = new OperateModel();
                    oper.Data = material;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                    #endregion
                }

                #endregion

                #region 计算新码的单价   关联条码的单价 * 使用的主计量数量   总和   /新码的主计量数量（去外面方法取值）
                string number = "";
                if (sysUnit == "kg")
                {
                    number = b["useWeight"].ToString();
                }
                else
                {
                    number = b["useMeter"].ToString();
                }
                barPrice += double.Parse(uCost) * double.Parse(number);
                #endregion

                #region 关联条码  先调拨再材料出，可能部分出，所以关联条码状态不变
                reBarCodes += string.Format("{0},", b["barCode"].ToString());
                bar = new DbProductBarCode();
                bar.barCode = b["barCode"].ToString();
                //bar.barStatus = "bar-used";
                bar.proWeight = (double.Parse(b["proWeight"].ToString()) - double.Parse(b["useWeight"].ToString())).ToString("0.000");
                if (!string.IsNullOrWhiteSpace(b["useMeter"].ToString()))
                {
                    bar.proMeter = (double.Parse(b["proMeter"].ToString()) - double.Parse(b["useMeter"].ToString())).ToString("0.000");
                }
                if (sysUnit == "kg")
                {
                    bar.number = bar.proWeight;
                }
                else
                {
                    bar.number = bar.proMeter;
                }
                //bar.number = bar.proWeight;
                oper = new OperateModel();
                oper.Data = bar;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "barCode";
                operList.Add(oper);
                #endregion
            }
            reBarCodes = reBarCodes.TrimEnd(',');
            return mlist;

        }
        private void ReBarDoBak(string barCode, ref List<OperateModel> operList)
        {
            DbProductBarCode bar;
            if (!string.IsNullOrWhiteSpace(barCode))
            {
                var rBars = barCode.Split(",");
                foreach (string barStr in rBars)
                {
                    if (!string.IsNullOrWhiteSpace(barStr))
                    {
                        bar = new DbProductBarCode();
                        bar.barCode = barStr;
                        bar.barStatus = "bar-used";
                        oper = new OperateModel();
                        oper.Data = bar;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "barCode";
                        operList.Add(oper);
                    }
                }
            }
        }
        /// <summary>
        /// 获取计划工序打印条码
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult GetPlanPrintBars(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                var obj = JsonConvert.DeserializeObject<JObject>(datas);
                StringBuilder sb = new StringBuilder();
                sb.Append("select *, barStatusName as statusName, cu_customer as customerName from V_BarCode_Info where ");
                sb.Append(" planCode = '" + obj["plCode"].ToString() + "' and gxCode = '" + obj["gxCode"].ToString() + "'");
                sb.Append(" and barStatus !='bar-drop' order by id desc");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = JsonConvert.SerializeObject(cmd.TableTolist<PrintedBarcode>(table));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }

        /// <summary>
        /// 采购打码
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public ReturnResult PurchaseInPrint(string json)
        {
            StringBuilder sb = new StringBuilder();
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var queryData = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
                string barStatus = "need-out";
                if (queryData.ContainsKey("isCheck") && queryData["isCheck"].ToString() == "1")
                {
                    barStatus = "need-check";//复合工序条码需要进行检验
                }
                string erpCode = queryData["cCode"].Trim();

                #region 根据单位判断主计量存什么
                double number=0,printNum=0;
                if (queryData["unit"].ToString() == "kg")
                {
                    number =double.Parse(queryData["weight"]);
                    printNum =double.Parse(queryData["weight"]);
                }
                else
                {
                    number = double.Parse(queryData["proMeter"]);
                    printNum = double.Parse(queryData["proMeter"]);
                }
                double tTotal=Math.Round(double.Parse(queryData["printNumber"]) * number, 2);
                #endregion

                sb.Append("select isnull(sum(convert(decimal(18,3),printNum)),0) from bar_ProductBarCode_info ");
                sb.Append("where barStatus !='bar-drop' and U8relationCode='"+ erpCode + "' ");
                sb.Append("and  proCode='"+ queryData["cInvCode"].ToString() + "' and erpRowNo='"+ queryData["irowno"].ToString() + "'");
                var qTable = cmd.GetDataTable(sb.ToString());//已打印数量合计
                if (qTable.Rows.Count > 0)
                {
                    tTotal += double.Parse(qTable.Rows[0][0].ToString());
                }

                //// 测试用 否则根本打不了码
                //wNumber = 1.0;
                if (tTotal > double.Parse(queryData["iQuantity"]))
                {
                    rsl.Message = "打印数量已超入库数量，禁止打码"; return rsl;
                }

               
                var printNumber = int.Parse(queryData["printNumber"]);
                var barCodes = this.CreateCodeInfo("CG", "采购打码", "4", printNumber);
                if (barCodes == null)
                { 
                    rsl.Message = "批量条码生成失败";
                    return rsl;
                }
                var barCodeList = barCodes.Split(',');

                var bars = new List<DbProductBarCode>();

                var parObj = new JObject();
                sb.Clear();
                sb.Append("select typeCode from fun_Inventory_Info where proCode='"+ queryData["cInvCode"].Trim() + "'");
                var pqTable = cmd.GetDataTable(sb.ToString());
                if (pqTable.Rows.Count > 0)
                {
                    if (pqTable.Rows[0][0].ToString().Substring(0, 2) == "05")
                    {
                        sb.Clear();
                        sb.Append("select isnull(parValue,'') parValue from sys_parameters_info where isdel=0 ");
                        sb.Append("and parCode='cgCpPar'");
                        var parTable = cmd.GetDataTable(sb.ToString());
                        if (parTable.Rows.Count > 0 && !string.IsNullOrWhiteSpace(parTable.Rows[0][0].ToString()))
                        {
                            parObj = JsonConvert.DeserializeObject<JObject>(parTable.Rows[0][0].ToString());
                        }
                    }
                }
                else
                {
                    rsl.Message = "存货编码错误："+ queryData["cInvCode"].Trim();
                    rsl.Result = false;
                    return rsl;
                }

             
              
                foreach (var barCode in barCodeList)
                {
                    var barDic = new Dictionary<string, string>();
                    barDic["barCode"] = barCode;
                    barDic["barType"] = "CG";
                    barDic["U8relationCode"] = queryData["cCode"];
                    barDic["erpRowNo"] = queryData["irowno"];
                    barDic["proCode"] = queryData["cInvCode"];
                    barDic["proName"] = queryData["cInvName"];
                    barDic["memo"] = queryData["memo"];
                    barDic["wareHouse"] = queryData["cWhCode"];
                    barDic["number"] = number.ToString();
                    barDic["printNum"] = printNum.ToString();//初始打印数量
                    barDic["proWeight"] = queryData["weight"];
                    barDic["proMeter"] = queryData["proMeter"];
                    barDic["cu_iUnitCost"] = queryData["iUnitCost"];
                    if (queryData.ContainsKey("cBatch") && !string.IsNullOrWhiteSpace(queryData["cBatch"]))
                    {
                        barDic["cu_batch"] = queryData["cBatch"];
                    }
                    else
                    {
                        barDic["cu_batch"] = DateTime.Now.ToString("yyyyMMdd"); ;
                    }
                    barDic["status"] = "Y";
                    barDic["isInitial"] = "N";
                    barDic["barStatus"] = barStatus;
                    barDic["happenDate"] = getNowDate();
                    barDic["createtime"] = getNow();
                    barDic["createuser"] = queryData["userCode"];
                    barDic["unit"] = queryData["unit"];
                    barDic["boxCode"] = queryData["boxCode"];
                    barDic["cu_qualityLevel"] = queryData["cu_qualityLevel"];
                    barDic["cu_shelfLife"] = queryData["cu_shelfLife"];
                    barDic["cu_vendor"] = queryData["cVenCode"];
                    barDic["cu_shelfLifeUnit"] = queryData["cu_shelfLifeUnit"];


                    foreach (var obj in parObj)
                    {
                        if (obj.Value != null && !string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!barDic.ContainsKey(obj.Key.Trim()) || string.IsNullOrWhiteSpace(barDic[obj.Key.ToString().Trim()]))
                            {
                                barDic[obj.Key.ToString().Trim()] = obj.Value.ToString().Trim();
                            }
                        }
                    }

                    var bar = JsonConvert.DeserializeObject<DbProductBarCode>(JsonConvert.SerializeObject(barDic));
                    bars.Add(bar);
                    oper = new OperateModel();
                    oper.Data = bar;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                }

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }

                rsl.Data = barCodes;
                rsl.Message = JsonConvert.SerializeObject(bars);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public List<PrintedBarcode> GetPrintedBarcodes_ByRdrecord01_cCode_iRowNo(string json)
        {

            var list = new List<PrintedBarcode>();
            try
            {
                var jObj = JsonConvert.DeserializeObject<JObject>(json);

                var cCode = jObj["cCode"].ToString();
                var irowno = jObj["irowno"].ToString();

                var sql = $@"select bar.*,statusDic.name as statusName from bar_ProductBarCode_info bar 
left join sys_dictionaries_info statusDic on statusDic.code = bar.barStatus
left join fun_Customs_info cus on bar.cu_customer = cus.cuCode 
where bar.U8relationCode = '{cCode}' and bar.erpRowNo = '{irowno}' 
and bar.isInitial = 'N' and bar.barType = 'CG' and statusDic.types = 'bst'; ";
                var dt = cmd.GetDataTable(sql);

                list = cmd.TableTolist<PrintedBarcode>(dt);
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return list;
        }
        /// <summary>
        /// 获取计划工序关联条码列表
        /// </summary>
        /// <param name="plCode"></param>
        /// <param name="gxCode"></param>
        /// <returns></returns>
        public ReturnResult GetPlanGxBarCodes(string plCode, string gxCode, string spec)
        {
            rsl = new ReturnResult();
            try
            {
                var tuple = this.GxIndexInPlan(plCode, gxCode);

                var i = tuple.Item1;
                var lastGx = tuple.Item2;

                #region 已注释
                //StringBuilder sb = new StringBuilder();
                //// 如果是第一道工序
                //if (i == 0)
                //{
                //    sb.Append("select bar.barCode,bar.proCode,bar.proName,bar.number,bar.proMeter,bar.spec from pi_PlanMaterial_list m");
                //    sb.Append(" inner join V_BarCode_Info bar on bar.barCode=m.reBarCode ");
                //    sb.Append(" and bar.barStatus='bar-used' where m.plCode='" + plCode + $@"' and spec = '{spec}' ");
                //}
                //else
                //{
                //    sb.Append("select barCode,proCode,proName,number,proMeter,spec from V_BarCode_Info where ");
                //    sb.Append(" barStatus in ('need-in','bar-used') and planCode='" + plCode + "' and gxCode='" + lastGx + $@"' ");
                //}
                //sb.Append(" union ");
                //sb.Append("select barCode,proCode,proName,number,proMeter,spec from V_BarCode_Info where barStatus='need-in'");
                //sb.Append(" and planCode='" + plCode + "' and gxCode='" + gxCode + $@"' ");

                //rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                #endregion

                string msg = "";
                var table = getRealtionBars(i, lastGx, plCode, ref msg, spec);

                if (!string.IsNullOrEmpty(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }

                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(table);
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return rsl;
        }
        public ReturnResult GetPlanGxBarCodes_noSpec(string plCode, string gxCode)
        {
            rsl = new ReturnResult();
            try
            {
                var tuple = this.GxIndexInPlan(plCode, gxCode);

                var i = tuple.Item1;
                var lastGx = tuple.Item2;

                string msg = "";
                var table = getRealtionBars(i, lastGx, plCode, ref msg);

                if (!string.IsNullOrEmpty(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }

                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(table);

            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return rsl;
        }
        /// <summary>
        /// 分切条码打印
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult FenQieBarCodePrint(string datas)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                StringBuilder sb = new StringBuilder();
                DbProductBarCode bar;
                string reBars = "";

                var obj = JsonConvert.DeserializeObject<JObject>(datas);

                if (obj.Property("relationBar") == null || string.IsNullOrWhiteSpace(obj["relationBar"].ToString()))
                {
                    rsl.Message = "关联条码不允许为空"; return rsl;
                }
          
                var gxRsl = this.isCheckGx(obj["plCode"].ToString(), obj["gxCode"].ToString());
                var dic = new Dictionary<string, string>();
                if (gxRsl.Result)
                {
                    dic = (Dictionary<string, string>)rsl.Data;
                }

                var relaBar = obj["relativeBarCodes"].ToString();
                relaBar = relaBar.Replace(",", "','");
                sb.Clear();
                sb.Append("select * from bar_ProductBarCode_info where barCode in ('" + relaBar + "')");
                var db_BarInfos = cmd.GetDataTable<DbProductBarCode>(sb.ToString());
                if (db_BarInfos.Count < 1)
                {
                    rsl.Message = "关联条码无效"; return rsl;
                }
                string supCode = "";
                foreach (var db in db_BarInfos)
                {
                    if (!string.IsNullOrWhiteSpace(db.cu_vendor))
                    {
                        supCode = db.cu_vendor;
                        break;
                    }
                }
                #region 得到关联条码的重量合计 与新码重量进行比较
                double wTotal = 0, mTotal = 0;
                foreach (var qbar in db_BarInfos)
                {
                    if (!string.IsNullOrWhiteSpace(qbar.proMeter))
                    {
                        mTotal += double.Parse(qbar.proMeter);
                    }
                    if (!string.IsNullOrWhiteSpace(qbar.proWeight))
                    {
                        wTotal += double.Parse(qbar.proWeight);
                    }
                }
                double bwt = 0, bmt = 0;
                foreach (var b in obj["list"])
                {
                    if (!string.IsNullOrWhiteSpace(b["meter"].ToString()))
                    {
                        bmt += double.Parse(b["meter"].ToString());
                    }
                    if (!string.IsNullOrWhiteSpace(b["weight"].ToString())) 
                    {
                        bwt += double.Parse(b["weight"].ToString());
                    }
                }
                if (wTotal < bwt )
                {
                    rsl.Result = false;
                    rsl.Message = "新码重量或米数录入有误"; return rsl;
                }
                #endregion
                var bars = this.CreateCodeInfo("XR", "分切码", "4", obj["list"].Count());//获取条码

                var barArr = bars.Split(',');
                double barPrice = 0;//条码单价 
                var code = getTimeString();//操作编码
                List<Dictionary<string, object>> mlist = new List<Dictionary<string, object>>();
                if (obj.Property("relationBar") != null && !string.IsNullOrWhiteSpace(obj["relationBar"].ToString()))
                {
                    if (Tools.AppSettingHelper.ReadAppSettings("IsDevelop").ToString() != "1")
                    {
                        mlist = this.ReBarDo(obj["relationBar"].ToString(), obj["plCode"].ToString(), code, ref operList, ref reBars, ref barPrice);//关联条码处理
                    }
                }
                if (Tools.AppSettingHelper.ReadAppSettings("IsDevelop").ToString() != "1")
                {
                    #region 生成材料出库单
                    if (mlist.Count > 0)
                    {
                        #region 构建参数

                        #region 获取材料出库默认的 业务类型 、部门  、仓库
                        sb.Clear();
                        sb.Append("seleCt parValue,parCode from sys_parameters_info where parCode like '%Style' and isdel=0 ");
                        var table = cmd.GetDataTable(sb.ToString());

                        var crdcode = "22"; //旭日环境
                                            //crdcode = table.Rows[0][0].ToString();
                        crdcode = table.Select("parCode='pom_Rd_Style'")[0]["parValue"].ToString();

                        var dept = "5"; //旭日：3 生产部  5 库存部   本地 ：5 二车间
                        dept = table.Select("parCode='all_Dept_Style'")[0]["parValue"].ToString();

                        var wareHouse = "8";  //旭日:车间库
                                              //wareHouse = table.Select("parCode='pom_Ware_Style'")[0]["parValue"].ToString();
                        #region 查询条码库存（Ning）客户说不会出现多个仓库
                        var bs = reBars.Split(',');
                        var Bars = "";
                        for (int j = 0; j < bs.Length; j++)
                        {
                            Bars += "'" + bs[j].ToString() + "',";
                        }
                        Bars = Bars.TrimEnd(',');
                        sb.Clear();
                        sb.Append(" select wareHouse from bar_ProductBarCode_info where barCode in (" + Bars + ") ");
                        sb.Append(" group by wareHouse order by wareHouse desc ");
                        var wTable = cmd.GetDataTable(sb.ToString());
                        int wnum = 0;
                        foreach (DataRow r in wTable.Rows)
                        {
                            if (!string.IsNullOrWhiteSpace(r["wareHouse"].ToString()))
                            {
                                wareHouse = r["wareHouse"].ToString();
                                wnum++;
                            }
                        }
                        if (wnum > 1)
                        {
                            rsl.Message = "关联条码存在多个仓库！";
                            return rsl;
                        }
                        #endregion

                        #endregion

                        List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                
                        foreach (var s in mlist)
                        {
                            dic = new Dictionary<string, string>();
                            dic["proCode"] = s["proCode"].ToString();
                            dic["proName"] = "";
                            dic["number"] = s["number"].ToString();
                            dic["cu_batch"] = s["batch"].ToString();
                            dic["iunitcost"] = s["uPrice"].ToString();//单价

                            dic["plCode"] = obj["plCode"].ToString();//计划号

                            var total = decimal.Parse(s["uPrice"].ToString()) * decimal.Parse(s["number"].ToString());
                            dic["iprice"] = total.ToString();//总金额

                            list.Add(dic);
                        }

                        List<string> obars = new List<string>();
                        obars.Add(reBars);//出库条码

                        var baseCode = obj["baseCode"].ToString();
                        var userCode = obj["userCode"].ToString();

                        #endregion

                        U8Order order = new U8Order();
                        rsl = order.tyInOut(list, obars, wareHouse, crdcode, dept, baseCode, userCode, "MaterialOut");

                        var U8Codes = string.Empty;
                        var U8Message = string.Empty;
                        var errBarCodes = new List<string>();//调用接口失败的条码

                        if (rsl.Result)
                        {
                            if (rsl.Data != null)
                            {
                                List<InOutResult> iorList = new List<InOutResult>();
                                iorList = (List<InOutResult>)rsl.Data;
                                if (iorList.Count > 0)
                                {
                                    U8Codes = "";
                                    foreach (InOutResult ior in iorList)
                                    {
                                        if (!string.IsNullOrWhiteSpace(ior.SuccOrderCode))
                                        {
                                            #region 调用接口成功
                                            U8Codes += ior.SuccOrderCode + ",";

                                            #region 返回错误信息和错误条码
                                            ErrorResult err = (ErrorResult)ior.ErrorInfo;
                                            if (err != null)
                                            {
                                                if (!string.IsNullOrWhiteSpace(err.ErrorMsg))
                                                {
                                                    U8Message += JsonConvert.SerializeObject(err.BarCodes) + "：" + err.ErrorMsg + "\n";//U8返回来的错误信息
                                                }
                                            }
                                            #endregion

                                            #endregion
                                        }
                                        else
                                        {
                                            #region 返回错误信息和错误条码
                                            ErrorResult err = (ErrorResult)ior.ErrorInfo;
                                            if (err != null)
                                            {
                                                if (!string.IsNullOrWhiteSpace(err.ErrorMsg))
                                                {
                                                    U8Message += JsonConvert.SerializeObject(err.BarCodes) + "：" + err.ErrorMsg + "\n";//U8返回来的错误信息
                                                }
                                                if (err.BarCodes != null && err.BarCodes.Count > 0)
                                                {
                                                    errBarCodes.AddRange(err.BarCodes);
                                                }
                                            }
                                            #endregion
                                        }

                                    }
                                }
                            }
                            if (!string.IsNullOrWhiteSpace(U8Message))
                            {
                                U8Message = "U8接口错误：" + U8Message;
                                rsl.Message = U8Message;
                                rsl.Result = false;
                                return rsl;
                            }

                            _log.Info("(ProductsPlanPrint)打码时条码材料出库成功，单号为：" + U8Codes.TrimEnd(','));
                        }
                        else
                        {
                            _log.Info("(ProductsPlanPrint)打码时条码材料出库失败：" + rsl.Message);
                        }
                    }
                    #endregion
                }

                #region 获取关联计划计划的客户、执行标准、材质
                string cuName = "";
                string caizhi = "";
                string biaozhun = "";
                sb.Clear();
                sb.Append("select cuName,caizhi,biaozhun from V_PI_ProductPlan_info where plCode='" + obj["plCode"].ToString() + "' ");
                var dt = cmd.GetDataTable(sb.ToString());
                if (dt.Rows.Count > 0)
                {
                    cuName = dt.Rows[0]["cuName"].ToString();
                    caizhi = dt.Rows[0]["caizhi"].ToString();
                    biaozhun = dt.Rows[0]["biaozhun"].ToString();
                }
                #endregion

                DbBarPrintLogs bp;
                var barJson = JsonConvert.DeserializeObject<List<JObject>>(obj["relationBar"].ToString());
                int i = 0;

                barPrice = barPrice / barArr.Length;

                sb.Clear();
                sb.Append("select * from fun_Inventory_Info where isdel=0");
                var invInfo = cmd.GetDataTable(sb.ToString());

                foreach (var b in obj["list"])
                {
                    bar = new DbProductBarCode();
                    bar.barCode = barArr[i];
                    bar.proCode = b["proCode"].ToString();
                    var dr = invInfo.Select("proCode='"+ b["proCode"].ToString() + "'");
                    if (dr.Length > 0)
                    {
                        bar.unit = dr[0]["sysUnit"].ToString();
                    }
                    
                    bar.proName = b["proName"].ToString();
                    bar.cu_batch = obj["cu_batch"].ToString();
                    bar.boxCode = obj["cu_batch"].ToString();
                    bar.happenDate = obj["happenDate"].ToString();
                    bar.status = "Y";
                    bar.pusers= obj["pusers"].ToString();
                    bar.costPlan= obj["plCode"].ToString();
                    bar.cu_qualityLevel = db_BarInfos[0].cu_qualityLevel;
                    if (string.IsNullOrWhiteSpace(db_BarInfos[0].cu_shelfLife))
                    {
                        bar.cu_shelfLife = "1";
                    }
                    else
                    {
                        bar.cu_shelfLife = db_BarInfos[0].cu_shelfLife;
                    }
                    if (string.IsNullOrWhiteSpace(db_BarInfos[0].cu_shelfLifeUnit))
                    {
                        bar.cu_shelfLifeUnit = "年";
                    }
                    else
                    {
                        bar.cu_shelfLifeUnit = db_BarInfos[0].cu_shelfLifeUnit;
                    }

                    if (dic.ContainsKey("isLast") && dic["isLast"]=="1")
                    {
                        bar.cu_material =dic["caizhi"];
                        bar.zhxbz = dic["biaozhun"];
                    }
                    else
                    {//非最后一道工序，材质、标准关联条码数据
                        bar.cu_material = db_BarInfos[0].cu_material;
                        bar.zhxbz = db_BarInfos[0].zhxbz;
                    }

                    bar.barStatus = "need-in";
                    bar.barType = "SC";
                    bar.U8relationCode = "-";
                    bar.createtime = getNow();
                    bar.createuser = obj["userCode"].ToString();
                    bar.gxCode = obj["gxCode"].ToString();
                    bar.proMeter = b["meter"].ToString();
                    bar.planCode = obj["plCode"].ToString();
                    bar.relationBar = reBars;
                    bar.isInitial = "N";
                    bar.memo = "分切生成条码";
                    bar.cu_vendor = supCode;


                    // 现在是直接手动录入
                    double nWeight = double.Parse(b["weight"].ToString());
                    bar.proWeight = nWeight.ToString();

                    if (bar.unit == "kg")
                    {
                        bar.number = b["weight"].ToString();
                    }
                    else
                    {
                        bar.number = b["meter"].ToString();
                    }

                    bar.printNum = bar.number; //初始打印数量
                    bar.cu_iUnitCost = (barPrice / double.Parse(bar.number)).ToString("0.000");
                    bar.cu_customer = cuName;

                    oper = new OperateModel();
                    oper.Data = bar;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);

                    foreach (var rb in barJson)
                    {
                        #region 添加打印记录 
                        bp = new DbBarPrintLogs();
                        bp.newBar = barArr[i];
                        bp.weight = bar.proWeight;
                        bp.meter = bar.proMeter;
                        bp.oldBar = rb["barCode"].ToString();
                        bp.useWeight = (double.Parse(rb["useWeight"].ToString()) / barArr.Length).ToString("0.00");  //2025-02-17调整
                        bp.useMeter = (double.Parse(rb["useMeter"].ToString()) / barArr.Length).ToString("0.00");    //2025-02-17调整
                        //bp.useWeight = rb["useWeight"].ToString();
                        //bp.useMeter = rb["useMeter"].ToString();
                        bp.mCode = code;
                        oper = new OperateModel();
                        oper.Data = bp;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                        #endregion
                    }

                    i++;
                }
                
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                    if (rsl.Result)
                    {
                        rsl.Data = bars;
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
            return rsl;
        }
        /// <summary>
        /// 验证计划工序是否是最后一道工序
        /// </summary>
        /// <param name="plCode"></param>
        /// <param name="gxCode"></param>
        /// <returns></returns>
        public ReturnResult isCheckGx(string plCode,string gxCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from pi_ProductionPlan_gx where plCode='" + plCode + "'");
                sb.Append(" and isdel=0 order by gxOrder desc ");
                var gxTable = cmd.GetDataTable(sb.ToString());
                var lastGxCode = gxTable.Rows[0]["gxCode"].ToString();
                string isLast = "0",caizhi="",zxbz="";
                if (lastGxCode ==gxCode)
                {
                    isLast = "1";
                    sb.Clear();
                    sb.Append("select cuName,caizhi,biaozhun from V_PI_ProductPlan_info where plCode='" + plCode + "' ");
                    var qTable = cmd.GetDataTable(sb.ToString());
                    if (qTable.Rows.Count > 0)
                    {
                        caizhi = qTable.Rows[0]["caizhi"].ToString();
                        zxbz = qTable.Rows[0]["biaozhun"].ToString();

                    }
                }
                var dic = new Dictionary<string, string>();
                dic["isLast"] = isLast;
                dic["caizhi"] = caizhi;
                dic["biaozhun"] = zxbz;
                rsl.Result = true;
                rsl.Data = dic;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据条码编码获取条码信息(视图)
        /// </summary>
        /// <param name="barCode">条码编码</param>
        /// <returns></returns>
        public ReturnResult GetBarCodeInfoByCode(string barCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                //sb.Append("select b.* ,cCode,dDate,cInvName,cInvStd,cBatch,cVenName from V_BarCode_Info b ");
                sb.Append("select b.* ,cCode,dDate,case when cInvName is null then b.proName else cInvName end cInvName,case when cInvStd is null then b.spec else cInvStd end cInvStd,");
                sb.Append("case when cBatch is null and b.barType='SC' then b.boxCode when cBatch is null and b.barType!='SC' then b.cu_batch else cBatch end cBatch,");
                sb.Append("case when cVenName is null then b.vendorName else cVenName end  cVenName ");
                sb.Append("from V_BarCode_Info b ");
                sb.Append("left join V_U8_PurchasePrint p on b.U8relationCode=p.cCode and b.erpRowNo = p.irowno where barCode='" + barCode + "'");
                var list = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                foreach (var s in list)
                {
                    if (!string.IsNullOrEmpty(s["dDate"].ToString()))
                    {
                        s["dDate"] = s["dDate"].ToString().Substring(0,10);
                    }
                }

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据条码编码获取条码信息(视图)
        /// </summary>
        /// <param name="barCode">条码编码</param>
        /// <returns></returns>
        public ReturnResult getRelationBarInfo(string barCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select *  from V_BarCode_Info where barCode='" + barCode + "'");
                var list = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        // 获取相关条码列表
        public ReturnResult getRelationBarCodeList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                var plCode = json["plCode"].ToString();
                var gxCode = json["gxCode"].ToString();

                rsl = GetPlanGxBarCodes_noSpec(plCode, gxCode);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        public List<string> MatAuxRePrint_AutoSuggest(string json)
        {
            var list = new List<string>();
            try
            {
                var jObj = JsonConvert.DeserializeObject<JObject>(json);
                var input = jObj["text"].ToString();

                var matClassSql = $@"select parValue from sys_parameters_info where parCode = 'matClass';";
                var matDt = cmd.GetDataTable(matClassSql);

                var matValues_str = matDt.Rows[0]["parValue"].ToString();

                var auxClassSql = $@"select parValue from sys_parameters_info where parCode = 'auxClass';";
                var auxDt = cmd.GetDataTable(auxClassSql);

                var auxValues_str = auxDt.Rows[0]["parValue"].ToString();

                var wholeStr = matValues_str + "," + auxValues_str;

                var classFilters = wholeStr.Split(',');

                var filter = "";
                foreach (var cStr in classFilters)
                {
                    if (filter == "")
                    {
                        filter += $@" proCode like '{cStr}%' ";
                    }
                    else
                    {
                        filter += $@" or proCode like '{cStr}%' ";
                    }
                }

                var sql = $@"select top 10 barCode from bar_productbarcode_info where barCode like '%{input}%' and ({filter}) and barStatus != 'used-finish' ; ";
                var dt = cmd.GetDataTable(sql);

                foreach (var row in dt.AsEnumerable())
                {
                    list.Add(row["barCode"].ToString());
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);

            }
            return list;
        }
        public Dictionary<string, string> GetOldBarCodeInfo(string json)
        {
            var barDic = new Dictionary<string, string>();
            try
            {
                var jObj = JsonConvert.DeserializeObject<JObject>(json);

                var barCode = jObj["barCode"].ToString();

                var sql = $@"select top 1 * from V_BarCode_Info where barCode = '{barCode}';";
                var dt = cmd.GetDataTable(sql);

                var dic = cmd.TableToDictionary(dt);

                if (dic.Count > 0)
                {
                    barDic = dic.First();
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return barDic;
        }
        /// <summary>
        /// 原辅料重新打码
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public ReturnResult MatAuxRePrint(string json)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                StringBuilder sb = new StringBuilder();
                var queryData = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                var oldBarCode = queryData["oldBarCode"];
                var a = queryData["barDatas"].ToString();
                var List= JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(queryData["barDatas"].ToString());
                //var newMeter = queryData["newMeter"];
                //var newWeight = queryData["newWeight"];

                #region 查出旧条码信息
                sb.Append("select top 1 * from bar_ProductBarCode_info where barCode = '" + queryData["oldBarCode"] + "'");
                sb.Append(" and barStatus not in( 'used-finish','bar-drop') ");  //,'bar-finish' 可能有退货的
                var dt = cmd.GetDataTable(sb.ToString());
                if (dt.Rows.Count < 1)
                {
                    rsl.Message = "关联条码错误！";
                    return rsl;
                }
                #endregion

                var barType = dt.Rows[0]["barType"].ToString();
                //var proWeight = dt.Rows[0]["proWeight"].ToString();
                //var number = dt.Rows[0]["number"].ToString();
                //var proMeter = dt.Rows[0]["proMeter"].ToString();
                
                // 生成新条码
                var newBarCode = this.CreateCodeInfo(barType, "重新打码", "4", List.Count);

                if (newBarCode == null) { rsl.Message = "条码生成失败"; return rsl; }

                var weiRemaining = decimal.Parse(dt.Rows[0]["proWeight"].ToString()); //原码剩余重量
                var metRemaining = decimal.Parse(dt.Rows[0]["proMeter"].ToString()); //原码剩余数量

                #region 构建新码信息
                var barArr = newBarCode.Split(',');

                for (var i=0;i< List.Count;i++)
                {
                    var theNew = cmd.TableTolist<DbProductBarCode>(dt)[0];

                    theNew.Id = null;
                    theNew.barCode = barArr[i];
                    theNew.createtime = getNow();
                    theNew.happenDate = getNowDate();
                    theNew.createuser = queryData["userCode"];
                    theNew.relationBar = oldBarCode;
                    theNew.proWeight = List[i]["proWeight"].ToString();
                    theNew.proMeter = List[i]["proMeter"].ToString(); 
                    if(theNew.unit=="kg")
                        theNew.number = List[i]["proWeight"].ToString();
                    else
                        theNew.number = List[i]["proMeter"].ToString();

                    weiRemaining -= decimal.Parse(List[i]["proWeight"].ToString());
                    metRemaining -= decimal.Parse(List[i]["proMeter"].ToString());

                    oper = new OperateModel
                    {
                        Data = theNew,
                        Types = OperateModel.OperateType.Add
                    };

                    operList.Add(oper);
                }
                #endregion

             
                var theOld = cmd.TableTolist<DbProductBarCode>(dt)[0];
                if(weiRemaining==0 && metRemaining == 0)
                {
                    //原码使用完成，则修改条码状态为使用完成    否则将原码数量改为剩余数量
                    theOld.barStatus = "used-finish";
                }
                else
                {
                    theOld.proWeight = weiRemaining.ToString();
                    theOld.proMeter = metRemaining.ToString();
                    if (theOld.unit == "kg")
                        theOld.number = weiRemaining.ToString();
                    else
                        theOld.number = metRemaining.ToString();
                }
                oper = new OperateModel
                {
                    Data = theOld,
                    Types = OperateModel.OperateType.Edit,
                    Conditions = "id"
                };

                operList.Add(oper);


                #region 存在老条码占用情况，需要将老条码替换成新条码   已注释（仅数量更新使用补打，此处重新打码是将一码分为多码）
                //sb.Clear();
                //sb.Append("select id,barCode from pi_ProductsOccupation_list where isdel=0 and status='Y'");
                //sb.Append(" and barCode='" + queryData["oldBarCode"] + "'");
                //var table = cmd.GetDataTable(sb.ToString());
                //foreach (DataRow r in table.Rows)
                //{
                //    DbProductsOccupation zy = new DbProductsOccupation();
                //    zy.id = int.Parse(r["id"].ToString());
                //    zy.barCode = newBarCode;
                //    zy.memo = string.Format("条码替换:{0}→{1}", queryData["oldBarCode"], newBarCode);
                //    zy.deldate = string.Format("替换时间：{0}", getNow());
                //    oper = new OperateModel();
                //    oper.Data = zy;
                //    oper.Types = OperateModel.OperateType.Edit;
                //    oper.Conditions = "id";
                //    operList.Add(oper);
                //}
                #endregion


                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                    rsl.Data = newBarCode;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public List<string> PlateRoller_AutoSuggest(string json)
        {
            var list = new List<string>();
            try
            {
                var jObj = JsonConvert.DeserializeObject<JObject>(json);
                var input = jObj["text"].ToString();

                var sql = $@"select top 10 byBarCode from [V_fun_BanYangInfo] where byBarCode like '%{input}%';";
                var dt = cmd.GetDataTable(sql);

                foreach (var row in dt.AsEnumerable())
                {
                    list.Add(row["byBarCode"].ToString());
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
            return list;
        }

        //获取版辊信息
        public ReturnResult GetPlateRollerInfo(string jsonStr)
        {
            var view = new Dictionary<string, string>();
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonStr);

                var byBarCode = dic["byBarCode"];
                sb.Append("select isnull(p.cuName,'') cuName,b.* from V_fun_BanYangInfo b ");
                sb.Append("left join pi_ProductionPlan_info p on b.PPlan=p.plCode ");
                sb.Append(" where byBarCode like '%" + byBarCode + "%' and b.isdel=0");
                var table = cmd.GetDataTable(sb.ToString());
                var listDic = cmd.TableToDictionary(table);
                if (listDic.Count > 0)
                {
                    view = listDic[0];
                    sb.Clear();
                    sb.Append("select * from V_fun_BanYangPro where byBarCode like '%"+byBarCode+"%' and isdel = 0");
                    var proDt = cmd.GetDataTable(sb.ToString());
                    var proCodes = "";
                    var proNames = "";

                    foreach (DataRow row in proDt.Rows)
                    {
                        proCodes += row["proCode"];
                        proCodes += ",";

                        proNames += row["proName"];
                        proNames += ",";
                    }

                    proCodes = proCodes.TrimEnd(',');
                    proNames = proNames.TrimEnd(',');

                    view["proCode"] = proCodes;
                    view["proName"] = proNames;

                    view["qcDate"] = DateTime.Now.ToString("yyyy-MM-dd");

                    rsl.Result = true;
                    rsl.Data = view;
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return rsl;
        }
        /// <summary>
        /// 生产工序完成
        /// </summary>
        /// <param name="plCode"></param>
        /// <param name="gxCode"></param>
        /// <returns></returns>
        public bool SubProducePlanComplete(string plCode, string gxCode)
        {
            var result = false;
            try
            {
                var sql = $@"update [pi_ProductionPlan_gx] set isFinish = 1 
where plCode = '{plCode}' and gxCode = '{gxCode}'; ";

                result = cmd.UpdateSql(sql).Result;
            }
            catch (Exception ex)
            {

            }

            return result;
        }


        /// <summary>
        /// 选码入库
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult SelectBarIn(string barCodes, string wareHouse, string userCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            U8Order order = new U8Order();
            try
            {
                StringBuilder sb = new StringBuilder();
                List<string> bars = new List<string>();

                var arrs = barCodes.Split(',');

                barCodes = "";
                foreach (var bar in arrs)
                {
                    bars.Add(bar);
                    barCodes = barCodes + "'" + bar + "',";
                }

                sb.Append("select * from V_BarCode_Info ");
                sb.Append(" where barCode in (" + barCodes.TrimEnd(',') + ") and barStatus='need-in'");
                var list = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));

                var baseCode = list[0]["baseCode"].ToString();

                #region 获取产成品入库默认的 业务类型 和部门
                sb.Clear();
                sb.Append("seleCt parValue,parCode from sys_parameters_info where parCode like '%Style' and isdel=0 ");
                var table = cmd.GetDataTable(sb.ToString());

                var crdcode = "12"; //旭日环境
                crdcode = table.Select("parCode='piw_Rd_Style'")[0]["parValue"].ToString();

                var dept = "5"; //旭日：3 生产部  5 库存部   本地 ：5 二车间
                dept = table.Select("parCode='all_Dept_Style'")[0]["parValue"].ToString();
                #endregion

                rsl = order.tyInOut(list, bars, wareHouse, crdcode, dept, baseCode, userCode, "ProductIn");

                #region 调用U8接口返回的数据
                var U8Code = string.Empty;
                var U8Message = string.Empty;
                var U8Codes = string.Empty;
                var errBarCodes = new List<string>();//调用接口失败的条码

                //false  返回
                if (!rsl.Result)
                {
                    rsl.Result = false;
                    var message = "接口返回的单据号为空" + "\n";
                    if (rsl.Message != null && !string.IsNullOrWhiteSpace(rsl.Message.ToString()))
                    {
                        message += "U8错误：" + rsl.Message.ToString();//U8返回来的错误信息
                    }
                    rsl.Message = message;
                    _log.Info("【选码入库】生成单据失败:" + message);
                    return rsl;
                }

                #region 添加出入库记录
                if (rsl.Data != null)
                {
                    List<InOutResult> iorList = new List<InOutResult>();
                    iorList = (List<InOutResult>)rsl.Data;
                    if (iorList.Count > 0)
                    {
                        U8Codes = "";
                        foreach (InOutResult ior in iorList)
                        {
                            if (!string.IsNullOrWhiteSpace(ior.SuccOrderCode))
                            {
                                #region 调用接口成功
                                U8Codes += ior.SuccOrderCode + ",";
                                #region 构建参数数组
                                var barList = ior.SuccBarCodes;
                                var cCode = getTimeString();//单据的临时编码
                                Dictionary<string, object> tempdic = new Dictionary<string, object>();
                                tempdic.Add("mCode", cCode);//临时编码
                                tempdic.Add("inOutType", "piw");
                                tempdic.Add("outOrderCode", ior.SuccOrderCode);//U8单号
                                tempdic.Add("baseCode", baseCode);
                                tempdic.Add("barList", barList);
                                tempdic.Add("wareHouse", wareHouse);
                                tempdic.Add("userCode", userCode);
                                #endregion

                                #region 添加主表和子表出入库记录    修改条码状态
                                insertMain(tempdic, list, crdcode, dept, ref operList);
                                rsl = insertList(tempdic, list, ref operList, null);
                                if (!rsl.Result)
                                {
                                    return rsl;
                                }
                                #endregion

                                #region 返回错误信息和错误条码    
                                ErrorResult err = (ErrorResult)ior.ErrorInfo;
                                if (err != null)
                                {
                                    if (!string.IsNullOrWhiteSpace(err.ErrorMsg))
                                    {
                                        U8Message += JsonConvert.SerializeObject(err.BarCodes) + "：" + err.ErrorMsg + "\n";//U8返回来的错误信息
                                    }
                                }
                                #endregion

                                #endregion
                            }
                            else
                            {
                                #region 返回错误信息和错误条码
                                ErrorResult err = (ErrorResult)ior.ErrorInfo;
                                if (err != null)
                                {
                                    if (!string.IsNullOrWhiteSpace(err.ErrorMsg))
                                    {
                                        U8Message += JsonConvert.SerializeObject(err.BarCodes) + "：" + err.ErrorMsg + "\n";//U8返回来的错误信息
                                    }
                                    if (err.BarCodes != null && err.BarCodes.Count > 0)
                                    {
                                        errBarCodes.AddRange(err.BarCodes);
                                    }
                                }
                                #endregion
                            }
                        }
                    }
                }
                #endregion


                rsl = cmd.MoreUpdate(operList);
                if (!rsl.Result)
                {
                    var temRsl = rsl;
                    return temRsl;
                }

                if (!string.IsNullOrWhiteSpace(U8Message))
                {
                    U8Message = "U8接口错误：" + U8Message;
                    rsl.Message = U8Message;
                    rsl.Result = false;
                    return rsl;
                }
                var U8cCode = "";
                if (!string.IsNullOrWhiteSpace(U8Codes))
                {
                    U8cCode = "保存成功，单号为：" + U8Codes.TrimEnd(',');
                    _log.Info("【选码入库】保存成功，单号为：" + U8Codes.TrimEnd(','));
                    rsl.Result = true;
                    rsl.Data = U8cCode;
                }

                rsl.Message = U8Message;

                #endregion
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
                _log.Info("【选码入库】生成单据异常:" + rsl.Message);
            }
            return rsl;
        }

        /// <summary>
        /// 出入库记录单主表
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="qList"></param>
        /// <param name="list"></param>
        private void insertMain(Dictionary<string, object> dic, List<Dictionary<string, string>> list, string rdCode, string dept, ref List<OperateModel> operList)
        {
            try
            {
                #region 反写出入库记录的主表
                DbBarRecordsMain main = new DbBarRecordsMain();
                main.happenDate = getNowDate();
                main.wareHouse = dic["wareHouse"].ToString();
                main.isBlue = "1";
                main.createuser = dic["userCode"].ToString();
                main.mType = rdCode;
                main.deptCode = dept;
                main.createtime = getNow();
                main.baseCode = dic["baseCode"].ToString();
                main.status = "needAudit";
                main.isCount = 0;
                main.maker = dic["userCode"].ToString();
                main.inOutType = dic["inOutType"].ToString(); //出入库类型
                main.outOrderCode = dic["outOrderCode"].ToString();//反写的单据号
                main.mCode = dic["mCode"].ToString();//临时编码
                main.isForm = "pc";//数据来源

                OperateModel oper = new OperateModel();
                oper.Data = main;
                oper.Types = OperateModel.OperateType.Add;

                operList.Add(oper);
                _log.Info("反写出入库记录主表单据号：" + dic["mCode"].ToString());
                #endregion
            }
            catch (Exception ex)
            {
                return;
            }
        }

        /// <summary>
        /// 出入库记录子表
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="qList"></param>
        /// <param name="list"></param>
        /// <param name="barCodes"></param>
        /// <param name="erridList"></param>
        /// <returns></returns>
        private ReturnResult insertList(Dictionary<string, object> dic, List<Dictionary<string, string>> list, ref List<OperateModel> operList, List<string> erridList)
        {
            try
            {
                #region 反写出入库单据明细表的数据
                var barList = (List<string>)dic["barList"];
                rsl = new ReturnResult();
                DbProductBarCode barInfo;
                OperateModel oper;
                foreach (var db in list)
                {
                    string barCode = db["barCode"];
                    if (barList != null && !barList.Contains(barCode))
                    {
                        continue;
                    }

                    #region 改变条码的状态
                    barInfo = new DbProductBarCode();

                    barInfo.Id = int.Parse(db["Id"].ToString());
                    //蓝单
                    barInfo.barStatus = "need-out";
                    barInfo.wareHouse = dic["wareHouse"].ToString();

                    oper = new OperateModel();
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Data = barInfo;
                    oper.Conditions = "Id";
                    operList.Add(oper);
                    #endregion

                    #region 出入库记录子表
                    DbBarRecordsList dl = new DbBarRecordsList();
                    dl.barCode = barCode;
                    dl.createtime = getNow();
                    dl.mCode = dic["mCode"].ToString();//临时编码
                    dl.num = db["number"].ToString();
                    dl.inOutType = dic["inOutType"].ToString();//出入库类型
                    dl.status = "Y";
                    dl.createuser = dic["userCode"].ToString();

                    oper = new OperateModel();
                    oper.Data = dl;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);

                    #endregion

                    rsl.Result = true;
                }
                #endregion
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }



    }
}
